Simulating LIKE in PHP

后端 未结 4 527
忘掉有多难
忘掉有多难 2021-01-05 05:21

Is there a way to simulate the LIKE operator of SQL in PHP with the same syntax? (% and _ wildcards and a generic $escape escape chara

4条回答
  •  有刺的猬
    2021-01-05 05:41

    The other examples were a bit too complex for my taste (and painful to my clean code eyes), so I reimplemented the functionality in this simple method:

    public function like($needle, $haystack, $delimiter = '~')
    {
        // Escape meta-characters from the string so that they don't gain special significance in the regex
        $needle = preg_quote($needle, $delimiter);
    
        // Replace SQL wildcards with regex wildcards
        $needle = str_replace('%', '.*?', $needle);
        $needle = str_replace('_', '.', $needle);
    
        // Add delimiters, beginning + end of line and modifiers
        $needle = $delimiter . '^' . $needle . '$' . $delimiter . 'isu';
    
        // Matches are not useful in this case; we just need to know whether or not the needle was found.
        return (bool) preg_match($needle, $haystack);
    }
    

    Modifiers:

    • i: Ignore casing.
    • s: Make dot metacharacter match anything, including newlines.
    • u: UTF-8 compatibility.

提交回复
热议问题