PHP - 使用数据库LIKE语法/通配符(%,_)搜索字符串

时间:2015-07-30 20:50:33

标签: php regex string sql-like

我有一个应用程序使用数据库LIKE表示法的语法接收搜索请求(例如:%someth_ng%),但我必须能够将此搜索不仅应用于数据库(这是直截了当的),但我的应用程序中的字符串,这是在PHP。

我认为使用正则表达式可能是最好的方法,但我想看看其他人可以提出的解决方案。

1 个答案:

答案 0 :(得分:0)

经过一番努力,这是我能想到的最好成绩:

public function like($needle, $haystack)
{
    // Escape meta-characters from the string so that they don't gain special significance in the regex
    $needle = preg_quote($needle, '~');

    // Replace SQL wildcards with regex wildcards
    $needle = str_replace('%', '.*', $needle);
    $needle = str_replace('_', '.', $needle);

    // Add delimiters, modifiers and beginning + end of line
    $needle = '~^' . $needle . '$~isu';

    return (bool) preg_match($needle, $haystack);
}

我很想知道是否有更好的解决方案或改进此解决方案。