替换单个字符或多个字符


Replacing single character or multiples of character

我想替换换行符'n。如果出现一个事件,则会将其替换为<br>。如果一行中有两个或多个,则用<br><br>替换。我可以选择其中一个或,但我不确定如何对同一变量同时执行这两个操作。

如果您想用相同数量的换行符替换两个或多个换行符,str_replace应该可以。

str_replace("'n", '<br />', $text);

但是,如果您只想用两个换行符替换三个换行符,则必须执行两次替换,至少一次使用正则表达式:

$text = preg_replace('/'n{2,}/', "<br /><br />", $text);
$text = str_replace("'n", '<br />', $text);

怎么样:

$pattern = array("/'n'n+/", "/'n/");
$replacement = array('<br/><br/>',  '<br/>' );
$str = "The quick 'nbrown fox 'n'n'njumps over 'n'nthe lazy dog.";
$result = preg_replace($pattern, $replacement, $str);

只需替换<br/>其中<br>如果<br>这才是你真正想要的。

作为Godwin解决方案的一个(希望更简单)变体,请尝试:

$text = str_replace("'n'n", '<br /><br />', $text);
$text = str_replace("'n", '<br />', $text);

这将用2个换行符替换任何2个连续的换行符,然后如果还有任何单个换行符,它们将被单个换行符替换。这将实现对1、2或3(或更多)个连续换行的替换。