您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

PHP无需数据库查询即可执行SQL LIKE匹配的方法?

PHP无需数据库查询即可执行SQL LIKE匹配的方法?

根据tomalak的评论和OIS使用preg_grep的绝妙想法,这可能更符合最终解决方案的要求。

<?PHP

function convertLikeToRegex( $command )
{
    return "/^" . str_replace( '%', '(.*?)', preg_quote( $command ) ) .  "$/s";
}

function selectLikeMatches( $haystack, $needle )
{
    return preg_grep( convertLikeToRegex( $needle ), $haystack );
}

$likeClauses = array(
    '%foo'
    ,'foo%'
    ,'%foo%'
);

$testInput = array(
    'foobar'
    ,'barfoo'
    ,'barfoobaz'
);

foreach ( $likeClauses as $clause )
{
    echo "Testing $clause:";
    echo '<pre>';
    print_r( selectLikeMatches( $testInput, $clause ) );
    echo '</pre>';
}

这是您追求的目标吗?

<?PHP

function convertLikeToRegex( $command )
{
    return "/^" . str_replace( '%', '(.*?)', $command ) .  "$/s";
}

$likeClauses = array(
    '%foo'
    ,'foo%'
    ,'%foo%'
);

$testInput = array(
    'foobar'
    ,'barfoo'
    ,'barfoobaz'
);

foreach ( $testInput as $test )
{
    foreach ( $likeClauses as $clause )
    {
        echo "Testing '$test' against like('$clause'): ";
        if ( preg_match( convertLikeToRegex( $clause ), $test ) )
        {
            echo 'Matched!';
        } else {
            echo 'Not Matched!';
        }
        echo '<br>';
    }
    echo '<hr>';
}
php 2022/1/1 18:35:29 有324人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶