mkoenig
1
I’ve been looking online for this solution figured i’d post the question up.
I know i did this years ago but can’t find the code and cant get a preg_match to work.
I want to check the variable $title that has been assigned for items in array and if there are any matches return a message or perform an action.
//example title
$title = "Me Brown wears a yellow hat sometimes";
//example array
$good = array("yellow","green","pink","blue","purple","black");
Any help is appreciated.
Thanks Sitepoint!
gvre
2
If you don’t need all matches, you can try the following
$title = "Me Brown wears a yellow hat sometimes";
$good = array("yellow", "brown", "green", "pink", "blue", "purple", "black");
$pattern = '#(' . implode("|", $good) . ')#i';
if (preg_match($pattern, $title))
{
echo "matches";
}
mkoenig
3
Thank you very much gvre you are the best that worked just fine.
Yeah i just needed 1 to match not all.
Thanks for the help!
If I understand well you want to check that an element from array exists in the string?
<?php
header("content-type:text/plain;charset=utf-8");
$_title = "Me Brown wears a yellow hat sometimes";
$_array = array("yellow","green","pink","blue","purple","black");
foreach($_array as $_item) {
if( preg_match("/$_item/", $_title) ) {
echo "{$_item} item found\
";
}
}
?>