我有一个由文本组成的字符串,可以包含多个\和n。
在 php 中,使用 preg_replace,我只想在需要的地方\n替换[NewLine]。说替换\n我的意思是替换字符反斜杠-n(\和n)。
我浏览了类似的问题,但没有找到一个来处理\\n不应该用新行替换的情况。
例如,字符串hello\nworld应该是hello[NewLine]world,
并且字符串hello\\nworld应该是hello\nworld.
意义 :
<?php
$source1 = <<<'EOD'
\n
EOD;
$source2 = <<<'EOD'
\\n
EOD;
$source3 = <<<'EOD'
\\\n
EOD;
//$source4 with 4 backslaskes , 5 with 5 etc.
//preg_replace `$source1` so it ends up as `[NewLine]`
//preg_replace `$source2` to `\\n`
//preg_replace `$source3` to `\\[NewLine]`
//etc
//....
//even number of consecutive \ followed by n means no [NewLine]
//odd number of consecutive \ followed by n means new [NewLine]
我有一个错误的替换代码
$a = preg_replace('{([^{\\\}])\\\n}', "$1\n", $string);
//work as expected when $string is "first-line\\nsecond-line";
//doesn't work as expected when $string is "first-line\\\nsecond-line";
任何人都知道在正则表达式中需要做什么才能使它正常工作?
蛊毒传说
万千封印
慕妹3146593