Attila Herbert
Attila Herbert

Reputation: 309

Counting occurrences of a string in a string

My question is the following:

Is there a string function that returns a count of occurrences, like substr_count(), but with a limiting option? I want to count the occurrences of 'a' in a string, but before the first newline.

Upvotes: 4

Views: 107

Answers (2)

Amal Murali
Amal Murali

Reputation: 76666

You can use substr() with strpos() to grab everything before the newline character, and then use substr_count() to get the number of occurrences:

$text = substr($string, 0, strpos($string, "\n"));
echo substr_count($text, $needle);

Demo!

Upvotes: 4

Matt S
Matt S

Reputation: 15364

I would use preg_match_all. It returns the count of matches. With a regex you can easily stop on a newline.

(Note: Amal's substr solution is faster than using a regular expression.)

Upvotes: 1

Related Questions