php - preg_match: can't find substring which has trailing special characters -
i have function uses preg_match check if substring in string. today realize if substring has trailing special characters special regular expression characters (. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -) or @, preg_match can't find substring though there.
this works, returns "a match found."
$find = "website scripting"; $string = "php website scripting language of choice."; if (preg_match("/\b" . $find . "\b/i", $string)) { echo "a match found."; } else { echo "a match not found."; }
but doesn't, returns "a match not found."
$find = "website scripting @"; $string = "php website scripting @ language of choice."; if (preg_match("/\b" . $find . "\b/i", $string)) { echo "a match found."; } else { echo "a match not found."; }
i have tried preg_quote, doesn't help.
thank suggestions!
edit: word boundary required, that's why use \b. don't want find "phone" in "smartphone".
you can check if characters around search word not word characters look-arounds:
$find = "website scripting @"; $string = "php website scripting @ language of choice."; if (preg_match("/(?<!\\w)" . preg_quote($find, '/') . "(?!\\w)/i", $string)) { echo "a match found."; } else { echo "a match not found."; }
see ideone demo
result: a match found.
note double slash used \w
in (?<!\\w)
, (?!\\w)
, have escape regex special characters in interpolated strings.
the preg_quote
function necessary search word - see - can have special characters, , of them must escaped if intended matched literal characters.
update
there way build regex smartly placed word boundaries around keyword, performance worse compared approach above. here sample code:
$string = "php website scripting @ language of choice."; $find = "website scripting @"; $find = preg_quote($find); if (preg_match('/\w$/u', $find)) { // setting trailing word boundary $find .= '\\b'; } if (preg_match('/^\w/u', $find)) { // setting leading word boundary $find = '\\b' . $find; } if (preg_match("/" . $find . "/ui", $string)) { echo "a match found."; } else { echo "a match not found."; }
Comments
Post a Comment