0

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

halfer
  • 19,824
  • 17
  • 99
  • 186
SuUbha
  • 167
  • 2
  • 15

1 Answers1

2

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
)
Toto
  • 89,455
  • 62
  • 89
  • 125
  • Hi, I need another help on this. The method you showed is return 'php' in result if the array has value 'php' in it. But I dont need it. so is there any way to return the value with a fixed length of the array value. that is the result should contain 'aphp','phpb'(fixed length 4). but result should not contain 'php'. – SuUbha May 10 '17 at 06:39
  • @SuUbha: Change the quantifiers `{0,2}` into `{1,2}`, see my edit. – Toto May 10 '17 at 07:12