MeltingDog MeltingDog - 1 year ago 115
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?

Answer Source

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

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

But foreach is 3x faster..

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download