Search code examples
phppreg-replacesymbolsapostrophe

preg_replace between something without removing the something


What i'm gonna do is:

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;

the output expected is:

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

but, the real output (which is not as expected):

Hi, your name is noname and she is noname.

How to keep the symbol ??

anybody can help me???

sorry, i just edit my question to show the actual things i wanna do.


Solution

  • You simply need to use preg_quote for escaping characters like 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;
    

    The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

    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.

    So you don't need to ---> \* that backslash for escaping as preg_quote in itself escape those characters

    Docs

    Demo