douxiao0400
2015-07-30 20:50
浏览 147
已采纳

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

This question already has an answer here:

I have an application receiving search requests using the syntax of a database LIKE notation (ex: %someth_ng%), but I must be able to apply this search not only to a database (which is straightforward), but to strings in my application, which is in PHP.

I'm thinking that using a regex is probably the best way to do this, but I'd like to see what solutions other people can/have come up with.

</div>

图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 这里有一个答案:

  • 在PHP中模拟LIKE 4 answers \ r

    我有一个应用程序使用数据库 LIKE 表示法的语法接收搜索请求(例如: %someth_ng%),但我必须能够将此搜索不仅应用于数据库(这很简单),而且应用于我的应用程序中的字符串,即PHP中的字符串。 < 我正在考虑使用正则表达式可能是最好的方法,但我想看看其他人可以提出的解决方案。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dsgni26260 2015-07-30 20:50
    最佳回答

    After a bit of work, this is the best I could come up with:

    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);
    }
    

    I'm curious to see if there are any better solutions, or improvements to this one.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题