简体   繁体   中英

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

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

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