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


Replace continuous occurrence of strings with single

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

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

您可以尝试此替代方法。

$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

.

如果您知道要替换的字符子集,例如 '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 个空格。