我有一个应用程序使用数据库LIKE
符号(例如:%someth_ng%
)的语法接收搜索请求,但我必须能够不仅将此搜索应用于数据库(这是直接的),而且应用于我的应用程序中的字符串,这是在PHP中。
我认为使用正则表达式可能是最好的方法来做到这一点,但我想看看其他人可以/已经提出了什么解决方案。
经过一些工作,这是我能想出的最好的:
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);
}
我很想知道是否有更好的解决方案,或改进这个