MeltingDog MeltingDog - 2 months ago 8
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
substr_count()
to achieve this?

Eg:
substr_count($str, $myRange);


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

Answer

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

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

But foreach is 3x faster..

Comments