Search code examples
phparrayspreg-grep

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


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

Solution

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