繁体   English   中英

reg表达式-用新行替换所有情况下的文本-php

[英]reg expression - replace text with new line for all occurances - php

我正在尝试使用正则表达式将“ XYZ”替换为“ \\ n”换行符。 但我没有成功。 请检查以下代码,并帮助我。

$epText = "this is for text |XYZ and |XYZ and XYZ";
$find = '|XYZ';
$replace = '\n';
$epFormatedText = preg_replace_callback(
    '/{{.+?}}/',
    function($match) use ($find, $replace) {
        return str_replace($find, $replace, $match[0]);
    },
    $epText
  );
 echo $epFormatedText;

但这是显示原始文本。 不执行任何操作。 请帮忙。

原因是您在$replace使用\\n前后的单引号。 这样, \\n被视为文字\\ + n字符。

至于正则表达式,我建议使用(?<!\\w)(?!\\w)环顾四周,因为您要匹配整个单词,而不是其他较长单词的一部分(根据您的示例判断)。

由于输入( $find )可以包含特殊的正则表达式元字符,因此您需要使用preg_quote来转义那些符号。

这是您的固定代码:

$epText = "this is for text |XYZ and |XYZ and XYZ";
$find = '|XYZ';
$replace = "\n";
$epFormatedText = preg_replace(
    "/(?<!\\w)" . preg_quote($find) . "(?!\\w)/",
    $replace,
    $epText
  );
 echo $epFormatedText;

IDEONE演示

您以错误的方式进行操作,只需要preg_replace即可,就像

$epText = "this is for text |XYZ and |XYZ and XYZ";
$find = '|XYZ';
$replace = '\n';

echo preg_replace("/\B" . preg_quote($find) . "\b/","\n",$epText);

注意:请注意在此处使用引号。

演示

preg_replace应该执行您需要的操作时,就不需要如此复杂的功能。

$epText = "this is for text XYZ and XYZ and XYZ";
$replaced = preg_replace('@XYZ@',"\n",$epText);

echo '<textarea>', $replaced ,'</textarea>';

尝试这个

echo  preg_replace('/XYZ/', '<br>', $epText);

暂无
暂无

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

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