简而言之 使用单个字符串值更改我们指定的字符串值的连续出现。 即
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);
答案 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
$str = str_replace(array("\t", ' '), ' ', $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