user188962
user188962

Reputation:

count new lines in textarea to resize container in PHP?

I have a textarea submitted to a php file.

Im using this to make it look exactly as the user entered the text:

 $ad_text=nl2br(wordwrap($_POST['annonsera_text'], 47, "\n", true));

If I want to resize a container I must be able to read how many lines are in the variable '$ad_text'.

Is there a way to do this...

I am still learning so thanks for your help...

Upvotes: 0

Views: 2739

Answers (3)

just somebody
just somebody

Reputation: 19247

$lines = explode("\n", $text);
$count = count($lines);
$html = implode($lines, "<br>");

Upvotes: 0

NawaMan
NawaMan

Reputation: 25687

You can use regular expression:

preg_match_all("/(\n)/", $text, $matches);
$count = count($matches[0]) + 1; // +1 for the last tine

EDIT: Since you use nl2br so '\n' is replaced by <br>. So you need this code.

preg_match_all("/(<br>)/", $text, $matches);
$count = count($matches[0]) + 1; // +1 for the last tine

However, <br> will not be display as newline in textarea (if I remember correctly) so you may need to remove nl2br.

Hope this helps.

Upvotes: 0

Richard Levasseur
Richard Levasseur

Reputation: 14892

You want the substr_count function.

Upvotes: 4

Related Questions