正则表达式-用新行替换所有出现的文本- 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字符。

对于regex,我建议使用(?<!'w)(?!'w)查找,因为您正在寻找匹配整个单词,而不是其他较长单词的部分(根据您的示例判断)。

由于输入($find)可能包含特殊的regex元字符,您需要使用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 demo

你这样做是错误的方式,你只需要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);