简体   繁体   中英

php preg_grep exact match

Okay so at the moment I'm using,

Preg_grep("/$query/", $file);

which basically takes the text sent via postmethod & checks whether it is in $file, but I could simply type " a " and it would output every match, i want it to be more specific.

So for example if I enter " Customer123 " which is in $file it will/should output " Customer123 " however if I type " Customer " then that shouldn't be enough to output customer123 so therefore return " Not found "..

You can use \\b before and after the expression to match it as a whole word

preg_grep("/\b$query\b/", $file);

Output:- https://eval.in/926867

To check for blank:-

if(trim($query) == ''){
   var_dump(preg_grep("/(^\$query*$)/", $file));

}else{
  var_dump(preg_grep("/\b$query\b/", $file));
}

Output:- https://eval.in/926939

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