Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace last occurrence of at least double new line (\n\n) in string PHP

I need to replace last occurrence of at least double new line (\n\n) in a string, so it should be \n\n or \n\n\n or \n\n\n\n an so on (at least 2 \n) by the "@@". I think that it should be preg_replace. I have tried many option that is in the answers here on stackoverflow, but all this options have some cases that was not catched. I tried regex101 site to prepare regular expression, but I am not strong in this, so I found some solution that looks like working on the site (/((\\n){2,})+(?!.*((\\n){2,})+)/i), but when I am trying it in my code, i doesn't work.

Another one was ([\\n\\n])+(.[^\\n\\n])*$, but this one catched also last nn

The test string was:

Storage\nThe powerful quad-core Intel X5 processor in Transformer Book T101HA means you'll have no problem breezing through all your everyday tasks,\nwith seamless multitasking allowing you to get more done in less time. Storage is conveniently flexible, too. Inside, there's 128GB of super-fast flash storage, and it's easily expandable via the micro SD card slot. You also get you a year's free unlimited cloud storage on ASUS WebStorage!\n\nColor|White/Gold\n\n\n\n\n\nCPU|Innn dsafdsfdfa \n\n\n\n\n\n\n\n dfnn

So the result should be:

Storage\nThe powerful quad-core Intel X5 processor in Transformer Book T101HA means you'll have no problem breezing through all your everyday tasks,\nwith seamless multitasking allowing you to get more done in less time. Storage is conveniently flexible, too. Inside, there's 128GB of super-fast flash storage, and it's easily expandable via the micro SD card slot. You also get you a year's free unlimited cloud storage on ASUS WebStorage!\n\nColor|White/Gold\n\n\n\n\n\nCPU|Innn dsafdsfdfa @@ dfnn

Can anyone help with this and maybe in addition explain the logic of the answered regex.

Thanks a lot.

like image 218
IncreMan Avatar asked Dec 25 '16 08:12

IncreMan


1 Answers

You may use

/\n{2,}(?!.*\n{2})/s

See the regex demo

Details:

  • \n{2,} - 2 or more newlines
  • (?!.*\n{2}) - not followed with any 0+ chars followed with 2 newlines.

If any linebreak is meant, replace \n with \R.

like image 135
Wiktor Stribiżew Avatar answered Nov 10 '22 04:11

Wiktor Stribiżew