2

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.

Syamsoul Azrien
  • 2,534
  • 4
  • 32
  • 55

2 Answers2

3

You could just include the quotes again in the replacement string:

$string="Hi, my name is 'Soul' and she is 'Maggie'. ";
$replace=preg_replace("/'(.*?)'/","'noname'",$string);
echo $replace;
trincot
  • 317,000
  • 35
  • 244
  • 286
sinaza
  • 820
  • 6
  • 19
2

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

Community
  • 1
  • 1
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54