preg_replace返回文字\ n而不是换行符

时间:2014-07-08 22:38:27

标签: php regex escaping newline

这个

$stringToSearch = "sometext\nold\nmoretext";
$old_val = "old";
$new_val = "new";
$replaceString = preg_replace('/\A(.+\n)?'.$old_val.'(\n.+)?\Z/', '${1}. "$new_val" . '${2}', $stringToSearch);

似乎没有保留$ stringToSearch中的原始换行符,但是将它们作为文字'\ n'返回,如下所示:

var_dump($replaceString);

产生

string(11) 
"sometext\nnew\nmoretext"

如何输出以下内容:

string(11) 
"sometext
new
moretext"

2 个答案:

答案 0 :(得分:0)

这对我有用:

$stringToSearch = "sometext\nold\nmoretext";
$old_val = "old";
$new_val = "new";
$replaceString = preg_replace('/\A(.+\n)?'.$old_val.'(\n.+)?\Z/', '${1}' . "$new_val" . '${2}', $stringToSearch);

var_dump ( $replaceString );

<强>输出:

string(21) "sometext
new
moretext"

答案 1 :(得分:0)

引号中的以下更改会提供您想要的输出。

<?php
$stringToSearch = "sometext\nold\nmoretext";
$old_val = "old";
$new_val = "new";
$replaceString = preg_replace('/\A(.+\n)?'.$old_val.'(\n.+)?\Z/', 
    "$1". "$new_val" . "$2", $stringToSearch);

var_dump($replaceString);
?>