MeltingDog MeltingDog - 4 months ago 22
PHP Question

PHP: Simple way to substr_count() where substring is array

I have a range of letters in an array:

$myRange = range("a","c");

I want to count how many times the letters in this range appear in a string:

$str = "abcdefg";

Is there a way I could use
to achieve this?

substr_count($str, $myRange);

I could use a foreach loop, but that seems overkill and not as elegant. Are loops the only way?


If you are using only single chars, you can use:

count( array_intersect( str_split( $str ), $myRange ) );

But foreach is 3x faster..