简体   繁体   中英

PHP preg_grep Variable

Using preg_grep, how would you search for an exact match of a variable? I was able to get the following code to return anything containing those letters, but can't seem to get only exact match.

$o is an array $a for example would be "at"

$c=preg_grep("/$a/",$o);
echo implode($c, ' ');

And the output would be something like: at cat hat mat

Using logic from bash grep I thought I could use ^\\$a$ but apparently isn't correct. Any ideas?

Vanilla PHP:

preg_grep('/\b' . preg_quote($a, '/') . '\b/', $o);

You can also use T-Regx

Pattern::inject('\b@\b', [$a])->forArray($o)->filter();

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