Count lines per line

I tried this: count newlines in textarea to resize container in PHP?

But it does not seem to work:

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

It will always output 1 .

Are there any other solutions for counting lines per line?

+6
source share
4 answers

Found this in one of my old applications ... 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 text box spits out html .. check <br> and <br/>

+11
source

You can try the following:

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

or

 $count = count(explode("\n", $_POST['text'])); 
+8
source
 count( explode(PHP_EOL, $str) ); 
+3
source

Use substr_count : -

  echo substr_count($str, '/\n|\r/'); 
0
source

Source: https://habr.com/ru/post/900441/


All Articles