Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading