Number of occurrences of \n in a string - PHP

Associate
Joined
8 Aug 2008
Posts
302
Hi

I need to work out how many linebreaks there are in a string so I can pad accordingly on a dynamic PDF output and I can't seem to work it out.

Thanks
 
A more robust way of doing it would be to normalize the line breaks first; this would account for the differences between line break characters used by various platforms.

PHP:
$normalizedString = str_replace("\r\n", "\n", $string); // Convert CRLF (Windows) to LF.
$normalizedString = str_replace("\r", "\n", $string); // Convert CR (Mac) to LF.

$count = substr_count("\n", $normalizedString);
 
Back
Top Bottom