Dan
Dan

Reputation: 12096

Counting php array occurrences in a string

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";

Upvotes: 1

Views: 256

Answers (2)

Matthew
Matthew

Reputation: 48284

You might find a regular expression to be useful:

$items = array('abc', 'def', 'ghi', 'etc');
$string = 'This is a string of text containing random abc def';

$appearsCount = count(preg_split('/'.implode('|', $items).'/', $string)) - 1;

Of course you have to take care not to invalidate the regular expression. (i.e., You'll need to properly escape the values in $items if 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.

Upvotes: 2

Nathaniel Ford
Nathaniel Ford

Reputation: 21220

Fastest, probably - at least you're unlikely to get much faster with arbitrary inputs. However, note that you may not be entirely correct:

$appearsCount = 0;

$string = "How many times is 'cac' in 'cacac'?";
$items = array("cac");

foreach($items as $item)
{
    $appearsCount += substr_count($string, $item);
}

echo "The item appears $appearsCount times";

Upvotes: 1

Related Questions