Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_replace $variable with string

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!

like image 205
RobinAlexander Avatar asked Oct 19 '25 14:10

RobinAlexander


1 Answers

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.
like image 193
Wiktor Stribiżew Avatar answered Oct 21 '25 03:10

Wiktor Stribiżew