preg_replace 在不删除某物的情况下

preg_replace between something without removing the something

我要做的是:

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.

如何保留符号??

谁能帮帮我???

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

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

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

你只需要使用 preg_quote 来转义像 as

这样的字符
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;

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

delimiter If the optional delimiter is specified, it will also be escaped. This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.

所以你不需要 ---> \* 那个反斜杠来转义,因为 preg_quote 本身转义那些字符

Docs

Demo