简体   繁体   中英

What am I doing wrong in this php regular expression?

Hello everyone currently I have a problem that I don't know what could be the cause, what I want to do is to know if an element of an array has a certain word, and I use this regular expression /.*example.*/ , and this is the code:

$array = ['example1', '2example', 'no'];

$matches = [];
$var = "example";

foreach($array as $element)
{
      preg_match("/.*$var.*/", $element, $matches);
}

But when I run that code and see the value of $matches it is an empty array. What am I doing wrong? I appreciate your help, thanks in advance:D.

That's because you are looping through your $array and probably print the result after the loop.

So $matches just includes the matching elements of the last item in your $array . But because 'no' is the last element, and it doesn't fulfill the regex requirements, $matches is empty.

To have a better understanding of what is happening, try to use print_r($matches) within your loop, after you called preg_matches() .

And after that, try to call it after your loop and see the difference.

You need two variables. One is the result of the current match, and another is a list of all the matches. After each call you can push the result of the current match to the list.

$array = ['example1', '2example', 'no'];

$matches = [];
$var = "example";

foreach($array as $element)
{
    if (preg_match("/.*$var.*/", $element, $match)) {
        $matches[] = $match[0];
    }
}

print_r($matches);

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