简体   繁体   English

替换单个字符或多个字符

[英]Replacing single character or multiples of character

I want to replace newline \n .我想替换换行符\n If there is one occurrence it gets replaced with <br> .如果出现一次,它将替换为<br> If there are two or more in a row it gets replaced with <br><br> .如果连续有两个或更多,它将被替换为<br><br> I can do either or but I am not sure how to do both for the same variable.我可以做任何一个,但我不确定如何为同一个变量做这两个。

If you want to replace two or more with the same number of line breaks, str_replace should work.如果你想用相同数量的换行符替换两个或更多,str_replace 应该可以工作。

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

If however, you want to replace three newline characters with only two line breaks then you'll have to perform two replaces, at least one using a regular expression:但是,如果您只想用两个换行符替换三个换行符,则必须执行两次替换,至少一次使用正则表达式:

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

How about:怎么样:

$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);

Just replace <br/> with <br> if <br> is what you really want.如果 <br> 是您真正想要的,只需将 <br/> 替换为 <br> 即可。

As a (hopefully simpler) variant of Godwin's solution, try:作为 Godwin 解决方案的一个(希望更简单的)变体,请尝试:

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

This will replace any 2 successive newlines with 2 line breaks, then if there are any single newlines remaining, they will be replaced by single line breaks.这将用 2 个换行符替换任何 2 个连续的换行符,然后如果还有任何单个换行符,它们将被单个换行符替换。 This would implement your substitutions for 1, 2, or 3 (or more) successive newlines.这将实现对 1、2 或 3(或更多)个连续换行符的替换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM