Nrc
Nrc

Reputation: 9797

Find and Replace 2 new lines in a string

I have a form and I want to find when there is 2 new lines in the text. I mean \n\n or <br/><br/> toguether. In his is an example I try to find the separation between Second and Third paragraph:

First paragraph  
Second paragraph 

Third paragraph

I can find one "\n" and replace, when there is just one new line:

$p = str_replace("\n", "replace", $text);

But I cannot find when there is 2 toguether. I try \n\n and <br/><br/> and it does not work:

$p = str_replace("\n\n", "replace", $text);

Upvotes: 1

Views: 163

Answers (1)

anubhava
anubhava

Reputation: 786329

You can instead take help of preg_replace:

 $p = preg_replace('/(\r?\n){2}/', "replace", $text)

This will replace 2 consecutive new line characters with word replace. It will also cover Windows new line characters i.e. \r\n

Upvotes: 3

Related Questions