Reputation: 309
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
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);
Upvotes: 4
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