I have a string and an array of values, I want to check how many times the items in an array appear within a string.
Is this the fastest way to do this?
$appearsCount = 0;
$string = "This is a string of text containing random abc def";
$items = array("abc", "def", "ghi", "etc");
foreach($items as $item)
{
$appearsCount += substr_count($string, $item);
}
echo "The item appears $appearsCount times";
You might find a regular expression to be useful:
Of course you have to take care not to invalidate the regular expression. (i.e., You’ll need to properly escape the values in
$itemsif they contain special characters in the context of a regular expression.)And this is not entirely the same thing as your multiple substring counts, as overlapping items will not be counted twice with the regular expression based split.