Replace the last occurrence of at least a double newline (\ n \ n) in the PHP line

I need to replace the last occurrence of at least a double new line ( \ n \ n ) in the line, so it should be \ n \ n or \ n \ n \ n or \ n \ n \ n \ n and so on ( at least 2 \ n ) " @@ ". I think this should be preg_replace . I tried many of the options that the answers have here on stackoverflow, but all of these options have some cases that were not detected. I tried the regex101 site to prepare a regular expression, but I'm not sure about it, so I found some solution that looked like working on the site ( /((\\n){2,})+(?!.*((\\n){2,})+)/i ), but when I try to use it in my code, I do not work.

The other was ([\\n\\n])+(.[^\\n\\n])*$ , but the latter also found nn

Test line:

Storing \ nYoung Intel X5 quad-core processor in Transformer Book T101HA means you won’t have a problem getting through all your everyday tasks, \ nwith seamless multitasking that lets you do more in less time. Storage is also convenient. Inside there is a 128 GB ultra-fast flash drive and is easily expandable through the Micro SD card slot. You also get free unlimited cloud storage per year on ASUS WebStorage! \ N \ nColor | White / Gold \ n \ n \ n \ n \ n \ nCPU | Innn dsafdsfdfa \ n \ n \ n \ n \ n \ n \ n \ n dfnn

Thus, the result should be:

Storing \ nYoung Intel X5 quad-core processor in Transformer Book T101HA means you won’t have a problem getting through all your everyday tasks, \ nwith seamless multitasking that lets you do more in less time. Storage is also convenient. Inside there is a 128 GB ultra-fast flash drive and is easily expandable through the Micro SD card slot. You also get free unlimited cloud storage for a year on ASUS WebStorage! \ N \ nColor | White / Gold \ n \ n \ n \ n \ n \ nCPU | Innn dsafdsfdfa @@ dfnn

Can anyone help with this and perhaps further explain the logic of the return regular expression.

Thank you very much.

+5
source share
1 answer

you can use

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

Watch the regex demo

More details

  • \n{2,} - 2 or more lines of a new line
  • (?!.*\n{2}) - do not follow any 0+ characters with two newlines.

If any line break is implied, replace \n with \R

+5
source

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


All Articles