1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.