用单个替换连续出现的字符串

时间:2013-10-28 18:23:41

标签: php

简而言之 使用单个字符串值更改我们指定的字符串值的连续出现。 即

hello \t\t\t\t\t world \n\n\n\n\t\t\t

hello \t world \n\t

详细

\n\tExample\n\r\nto \nunderstand\n\r\n the current\n situatuion\t\t\t\t\t.

我希望输出为

 Example
to 
understand
 the current
 situation .

输出html

<br /> Example<br />to <br />understand<br /> the current<br /> situation .

我设法获得此输出

Example

to 
understand

the current
situatuion .

使用此代码

$str='\n\tExample\n\r\nto \nunderstand\n\r\n the current\n situatuion\t\t\t\t\t.';


 echo str_replace(array('\n', '\r','\t','<br /><br />' ),
            array('<br />', '<br />',' ','<br />'), 
            $str);

2 个答案:

答案 0 :(得分:0)

如果您知道要替换的字符子集,例如\r\n\n\t,那么单个正则表达式应该可以替换所有重复的实例同样的:

/(\r\n|\n|\t)\1+/

您可以将其与PHP preg_replace()一起使用以获得替代效果:

$str = preg_replace('/(\r\n|\n|\t)\1+/', '$1', $str);

然后,要使输出“HTML友好”,您可以使用nl2br()str_replace()(或两者)进行另一次传递:

// convert all newlines (\r\n, \n) to <br /> tags
$str = nl2br($str);

// convert all tabs and spaces to &nbsp;
$str = str_replace(array("\t", ' '), '&nbsp;', $str);

作为备注,您可以使用\r\n|\n|\t替换上述正则表达式中的\s来替换“所有空格”(包括常规空格);我特意写了这个,因为你没有提到常规空格,以防你想要在列表中添加额外的字符来替换。

编辑更新了上面的\t替换,用每个评论澄清替换为单个空格而不是4个空格。

答案 1 :(得分:0)

您可以尝试这种替代方案。

$string = "\n\tExample\n\r\nto \nunderstand\n\r\n the current\n situation\t\t\t\t\t.";

$replacement = preg_replace("/(\t)+/s", "$1", $string);

$replacement = preg_replace("/(\n\r|\n)+/s", '<br />', $string);

echo "$replacement";

#<br /> Example<br />to <br />understand<br /> the current<br /> situation