简体   繁体   中英

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

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);

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM