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.

>Solution :

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

Leave a Reply