I have found several questions on this topic, but no solution for my purpose:
$name = 'Adam';
$line = 'This is (Adam) Eve!';
$newline = preg_replace('/\(|\)/|\$name/','',$line);
My output should be This is Eve
... Any idea what is wrong with my code? Thanks for your help!
In single quoted PHP string literals, variables are not expanded. Moreover, since the $
is escaped, it is matched as a literal char. \$name
matches $name
substring, not Adam
. Besides, /
before |
corrupts the whole pattern ending it prematurely.
Perhaps, you wanted to use
$name = 'Adam';
$line = 'This is (Adam) Eve!';
$newline = preg_replace("/\(|\)|$name/",'',$line);
echo $newline;
See the PHP demo. To get rid of the space before Eve
, add \s*
before $name
in the pattern to match 0+ whitespace chars.
Another alternative:
preg_replace("/\s*\($name\)/",'','This is (Adam) Eve!')
See another PHP demo.
Here,
\s*
- matches 0+ whitespace chars\(
- a (
char$name
- text inside $name
variable\)
- a literal )
char.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With