Well, after many fun and games here, what I came up with:
function preg_sql_like ($input, $pattern, $escape = '\\') {
$expr = '/((?:'.preg_quote($escape, '/').')?(?:'.preg_quote($escape, '/').'|%|_))/';
$parts = preg_split($expr, $pattern, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$expr = '/^';
$lastWasPercent = FALSE;
foreach ($parts as $part) {
switch ($part) {
case $escape.$escape:
$expr .= preg_quote($escape, '/');
break;
case $escape.'%':
$expr .= '%';
break;
case $escape.'_':
$expr .= '_';
break;
case '%':
if (!$lastWasPercent) {
$expr .= '.*?';
}
break;
case '_':
$expr .= '.';
break;
default:
$expr .= preg_quote($part, '/');
break;
}
$lastWasPercent = $part == '%';
}
$expr .= '$/i';
return (bool) preg_match($expr, $input);
}
I can’t break it, maybe you will find something that will be. The main way that mine differs from @nickb is that my "parses" (ish) the input expression in tokens to generate a regular expression, rather than converting it to a regular expression in situ.
. PCRE, , . , , - i, - - , , .
, , $input $pattern.
, , .
EDIT /: