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.
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);
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.)