preg_replace之间没有删除的东西

时间:2015-11-21 08:40:01

标签: php preg-replace symbols apostrophe

我要做的是:

function replace_between_something($betweenWhat,$replace_thing,$target){
return preg_replace("/".$betweenWhat."(.*?)".$betweenWhat."/",$replace_thing,$target);
}
$string="Hi, *my* name is 'Soul' and she is 'Maggie'. ";

$replace=replace_between_something("\*","your",$string);
$replace=replace_between_something("'","noname",$replace);

echo $replace;

预期的输出是:

Hi, *your* name is 'noname' and she is 'noname'.

但是,实际输出(不符合预期):

Hi, your name is noname and she is noname.

如何保持符号??

任何人都可以帮助我???

抱歉,我只是编辑我的问题,以显示我想要做的实际事情。

2 个答案:

答案 0 :(得分:3)

您可以在替换字符串中再次包含引号:

$string="Hi, my name is 'Soul' and she is 'Maggie'. ";
$replace=preg_replace("/'(.*?)'/","'noname'",$string);
echo $replace;

答案 1 :(得分:2)

您只需使用preg_quote来转义字符

function replace_between_something($betweenWhat, $replace_thing, $target) {
    return preg_replace("/" . preg_quote($betweenWhat) . "(.*?)" . preg_quote($betweenWhat) . "/", $betweenWhat.$replace_thing.$betweenWhat, $target);
}

$string = "Hi, *my* name is 'Soul' and she is 'Maggie'. ";

$replace = replace_between_something("*", "your", $string) . "\n";
$replace = replace_between_something("'", "noname", $replace);

echo $replace;

特殊正则表达式字符为:. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

  

<强>定界符   如果指定了可选的分隔符,它也将被转义。这对于转义PCRE函数所需的分隔符非常有用。 /是最常用的分隔符。

所以你不需要---> \*转义反斜杠,因为preg_quote本身可以逃避这些字符

Docs

Demo