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.
CodePudding user response:
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.
CodePudding user response:
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);