4

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!

Robin Alexander
  • 984
  • 2
  • 13
  • 29

3 Answers3

5

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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
2

Use strtr function instead of regular expression

$name = 'Adam';
$line = 'This is (Adam) Eve!';
$line = strtr($line, array('(' => '',$name=>'', ')' => ''));
Sanjit Bhardwaj
  • 893
  • 7
  • 13
1

First of all, you may want to learn about double and single enquoted strings in PHP.

Then your regex is wrongly formatted and is not what you want as well.

/\(|\)/|\$name/

Your regex has a syntax error with the slash )/| before the pipe and after the closing brackets. It is unescaped and is also the escape character for your regex. (Meaning it is also present at the start and end of your regex.) You need to remove it first.

You will get a regex that looks like this /\(|\)|\$name/. With it your function call has the following logic:

  1. Remove all opening brackets
  2. OR remove all closing brackets
  3. OR remove the string $name

That is clearly not what you want. You want to remove all occurances of the word in your $name variable, that are enclosed by brackets.

This can be achieved by the following function call:

$newline = preg_replace("/\($name\)/", '', $line);

If you want to make the brackets optional, use question mark operator to indicate, that they are not mandatory:

$newline = preg_replace("/\(?$name\)?/", '', $line);
Philipp Maurer
  • 2,480
  • 6
  • 18
  • 25