问题
I need to find any character before or after of a word using PHP preg_grep() from array. I have a array like following
$findgroup = array("aphp", "phpb", "dephpfs", "potatoes");
I need to find the values from the array which have 'php' word with a single or double character before or after(either side, not both side) the word 'php'. The result should be 'aphp','phpb' word from the array.
I tried with the following code but not works.
$result[] = preg_grep("/(.{1})php(.{1})/", $findgroup);
回答1:
Anchor your regex and add quantifier for character before and after:
$findgroup = array("aphp", "phpb", "dephpfs", "potatoes", "aphpb", "php");
$result = preg_grep("/^(?:.{1,2}php|php.{1,2})$/", $findgroup);
print_r($result);
Output:
Array
(
[0] => aphp
[1] => phpb
)
来源:https://stackoverflow.com/questions/43868798/find-character-before-or-after-of-string-using-preg-grep-in-php