Find character before or after of string using preg_grep() in PHP

妖精的绣舞 提交于 2019-12-02 19:06:22

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!