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!

3
  • Use correct SE terminology please. "I have found several questions on this problem", for example. Commented Jan 29, 2018 at 11:50
  • Try - \(Adam\)\s.. Commented Jan 29, 2018 at 11:52
  • Just take a look at this, may be it can help you Visit Commented Jan 29, 2018 at 11:59

3 Answers 3

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.
Sign up to request clarification or add additional context in comments.

Comments

2

Use strtr function instead of regular expression

$name = 'Adam';
$line = 'This is (Adam) Eve!';
$line = strtr($line, array('(' => '',$name=>'', ')' => ''));

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.