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
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.