PHP - 使用数据库搜索字符串 LIKE syntax/wildcards (%, _)
PHP - searching string with database LIKE syntax/wildcards (%, _)
我有一个应用程序使用数据库语法 LIKE
符号(例如:%someth_ng%
)接收搜索请求,但我必须能够将此搜索不仅应用于数据库(很简单),但对于我的应用程序中的字符串,它位于 PHP.
我认为使用正则表达式可能是最好的方法,但我想看看其他人 can/have 提出了什么解决方案。
经过一些工作,这是我能想到的最好的:
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);
}
我很好奇是否有更好的解决方案,或者对此有改进。
我有一个应用程序使用数据库语法 LIKE
符号(例如:%someth_ng%
)接收搜索请求,但我必须能够将此搜索不仅应用于数据库(很简单),但对于我的应用程序中的字符串,它位于 PHP.
我认为使用正则表达式可能是最好的方法,但我想看看其他人 can/have 提出了什么解决方案。
经过一些工作,这是我能想到的最好的:
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);
}
我很好奇是否有更好的解决方案,或者对此有改进。