PHP preg_grep -> search array where search term contains special character

121 views Asked by At

Trying to search an array that contains special characters:

$array=array("0|0Name"=>"first name","0|1last"=>"last name","1|0email"=>"email address");

tried

  $v="0|0";
  print_r(preg_grep("/^".$v.".*/",$array)); --->FAIL

tried:

  $v=str_replace("|","\|","0|0");
  print_r(preg_grep("/^".$v.".*/",$array)); --->FAIL
1

There are 1 answers

1
Davey Shafik On BEST ANSWER

Use preg_quote(), it will escape the special characters, taking into account the delimiter (in your case, /):

$v = preg_quote("0|0", "/");
print_r(preg_grep("/^".$v.".*/",$array));