替换字符串 PHP 中最后出现的至少两个新行 (\n\n)

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

我需要替换字符串中至少两次换行 (\n\n) 的 last occurrence,所以它应该是 \n\n\n\n\n\n\n\n\n 等等(至少 2 \n)由“@@”。我认为应该是preg_replace。我在 Whosebug 上的答案中尝试了很多选项,但所有这些选项都有一些未捕获的情况。我试过 regex101 网站来准备正则表达式,但我在这方面并不擅长,所以我找到了一些看起来像在网站上工作的解决方案 (/((\n){2,})+(?!.*((\n){2,})+)/i),但是当我在我的代码中尝试它时,我没有没用。

另一个是([\n\n])+(.[^\n\n])*$,但是这个也是最后一个nn

测试字符串是:

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

所以结果应该是:

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

任何人都可以帮助解决这个问题,也许还可以解释所回答的正则表达式的逻辑。

非常感谢。

您可以使用

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

regex demo

详情:

  • \n{2,} - 2 个或更多换行符
  • (?!.*\n{2}) - 后面没有任何 0+ 个字符,后跟 2 个换行符。

如果要换行,请将 \n 替换为 \R