PHP 中只允许连续一到两次回车 return
Allow only one or two consecutives carriage return in PHP
我卡在 preg_replace(我想这就是我需要的)合成器上。
我想从多个回车 return 中清除一个字符串(只允许最多 2 个跟在回车 return 之后,不能更多。)
因此这些字符串将保持不变:
- "Some text \n some text"
- "Some text \n\n some text \n some other text"
而这个需要找零钱:
- "Some text \n\n\n some text"
进入
- "Some text \n\n some text"
我想有一种简单的方法可以做到这一点,但我不习惯使用正则表达式,因此我们将不胜感激。
罗曼.
您可以使用这样的正则表达式:
\n\n\n+
使用替换字符串:
\n\n
代码
$re = "/\n\n\n+/";
$str = "\"Some text \n some text\"\n\n\"Some text \n\n some text \n some other text\"\n\nSome text \n\n\n some text";
$subst = "\n\n";
$result = preg_replace($re, $subst, $str);
我卡在 preg_replace(我想这就是我需要的)合成器上。
我想从多个回车 return 中清除一个字符串(只允许最多 2 个跟在回车 return 之后,不能更多。)
因此这些字符串将保持不变:
- "Some text \n some text"
- "Some text \n\n some text \n some other text"
而这个需要找零钱:
- "Some text \n\n\n some text"
进入
- "Some text \n\n some text"
我想有一种简单的方法可以做到这一点,但我不习惯使用正则表达式,因此我们将不胜感激。
罗曼.
您可以使用这样的正则表达式:
\n\n\n+
使用替换字符串:
\n\n
代码
$re = "/\n\n\n+/";
$str = "\"Some text \n some text\"\n\n\"Some text \n\n some text \n some other text\"\n\nSome text \n\n\n some text";
$subst = "\n\n";
$result = preg_replace($re, $subst, $str);