Reputation: 3
I am trying to figure out how to match any words within an array. For example, the code bellow works for finding "Test Name" within an array but does not find "Another Test Name" (due to the word "Another") within the array. Any ideas?
if (in_array($html[$i], $eventsarray))
{
$topeventaa = "yes";
}
else
{
$topeventaa = "no";
}
Upvotes: 0
Views: 4349
Reputation: 8003
Use preg_grep
instead of in_array
to find all elements of an array matching a given pattern.
Upvotes: 0
Reputation: 1075
Justin, there's no direct way--no existing built-in function--to do what I believe you seek; you must iterate over the array yourself, along the lines of
$topeventaa = "no";
for ($eventsarray as $key=>$value){
if (0 <= strpos($html[$i], $eventsarray[$key])) {
$topeventaa = "yes";
break;
}
}
Upvotes: 0
Reputation: 1258
You may want to look into recursive function calls, like when traversing through all the directories within a directory tree. I'd splice the array up to the index where it was found, leaving the remainder to be passed back into the same function to search through again. Depending on what results you want from knowing the number of occurrences of words within a string could we then start to break down the problem and write some code.
Upvotes: 0
Reputation: 538
We probably need more information, but you can create variable with the pattern matching you need with preg_match and pass it as the argument in your search.
preg_replace and str_replace may be helpful, depending on what exactly you're trying to accomplish.
Upvotes: 0
Reputation: 4766
If you want to match any of the words to those in your array, you may want to use explode on your string and then check each token as you do in your example.
Upvotes: 0
Reputation: 1090
Taken from http://php.net/manual/en/function.in-array.php
<?php
/**
* Takes a needle and haystack (just like in_array()) and does a wildcard search on it's values.
*
* @param string $string Needle to find
* @param array $array Haystack to look through
* @result array Returns the elements that the $string was found in
*/
function find ($string, $array = array ())
{
foreach ($array as $key => $value) {
unset ($array[$key]);
if (strpos($value, $string) !== false) {
$array[$key] = $value;
}
}
return $array;
}
?>
Upvotes: 2