9

I've tried this: count new lines in textarea to resize container in PHP?

But it doesn't seems to be working:

$content = nl2br($_POST['text']);
preg_match_all("/(<br>)/", $content, $matches);

echo count($matches[0]) + 1;

It'll always output 1.

Is there any other solutions to count lines in a string?

Community
  • 1
  • 1
Cyclone
  • 14,839
  • 23
  • 82
  • 114

3 Answers3

18

Found this in one of my old apps... Not sure where I got it from.

$lines_arr = preg_split('/\n|\r/',$str);
$num_newlines = count($lines_arr); 
echo $num_newlines;

*Edit - Actually, this probably won't work if your textarea is spitting out html.. check for <br> and <br/>

K2xL
  • 9,730
  • 18
  • 64
  • 101
11

You can try this:

$count = substr_count($_POST['text'], "\n") + 1;

or:

$count = count(explode("\n", $_POST['text']));
6
count( explode(PHP_EOL, $str) );
yckart
  • 32,460
  • 9
  • 122
  • 129