PHP Strings Primer - Counting Paragraphs
(Page 25 of 37 )
At times it might be beneficial to count the number of paragraphs, or the number of new lines, in some text that a user has entered. An elementary method of doing this is with the 'substr_count()' function. This function will count the number of occurrences of a given substring. for our example, we would count the number of newline characters.
<?php $text = "This is the first line. And this is the second. More text goes down here on the third.";
$lines = substr_count ($text, "\n"); echo ($lines); ?> |
After executing this code, '$lines' would contain the number 2. This isn't quite what we expected. The reason that this number is lower than we would expect is that the last line does not end with a newline character. We could simply add one to the result of the 'substr_count()' function, but this wouldn't work in all situations. What if there is a newline character at the end of the string? Then, our result would be inflated.
The answer is to check if the newline character exists or not at the end of the string. We can accomplish this with the 'strrchr()' function. This function will return the portion of the string from the last occurrence of the substring we search for to the end of the string. If we search for the newline character and are returned more than just that character then we know that there is not a newline character at the end of the string. In this case, we would add one to the count.
<?php $text = "This is the first line. And this is the second. More text goes down here on the third.";
$lines = substr_count ($text, "\n");
if (strrchr ($text, "\n") != "\n") { Â Â Â $lines++; } echo ($lines); ?> |
Next: Filtering Words >>
More Programming Basics Articles
More By Matt Wade