4

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.

2 Answers 2

4

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!

Sign up to request clarification or add additional context in comments.

1 Comment

This is a faster solution than my answer.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.