I have a preg_match matching for specific patterns, but it's just not matching the pattern I'm trying to match. What am I doing wrong?
<?php
$string = "tell me about cats";
preg_match("~\b(?:tell me about|you know(?: of| about)?|what do you think(?: of| about)?|(?:what|who) is|(?:whats|whos)) ((?:[a-z]+ ){1,2})$~", $string, $match);
print_r($match);
?>
Expected Result:
array(0 => tell me about 1 => cats)
Actual Result:
array()
You are having an extra space in (but there are no spaces after cat
making the entire regex to fail)
((?:[a-z]+ ){1,2})
^^
||
here
also, you don't have capturing group for first part (due to (?:..)
). Make a capturing group and make the spaces optional using ?
(if you want to capture at most two words)
\b(tell me about|you know(?: of| about)?|what do you think(?: of| about)?|(?:what|who) is|(?:whats|whos)) ((?:[a-z]+){1,2} ?)$
PHP Code
$string = "tell me about cats";
preg_match("~\b(tell me about|you know(?: of| about)?|what do you think(?: of| about)?|(?:what|who) is|(?:whats|whos)) ((?:[a-z]+ ?){1,2})$~", $string, $match);
print_r($match);
NOTE :- $match[1]
and $match[2]
will contain your result. $match[0]
is reserved for entire match found by the regex in the string.