Name
Name

Reputation: 149

Delete All Between ( and )

I want to replace everything between ( and ). And it also works with this preg_replace().

$return =  preg_replace("/\([^)]+\)/", "", $return);

If my $return is like "Hello my name is Frank (nicer guy)"

the string is "Hello my name is Frank"

But in case that between the Parentheses are also next Parentheses it does not work. For example:

before:

"Hello my name is Frank (nicer (guy) thank you)"

after

"Hello my name is Frank thank you)"

it stops after the first ")". Is it possible that it also deletes the Parentheses inside the Parentheses?

Upvotes: 0

Views: 142

Answers (2)

Kontrollfreak
Kontrollfreak

Reputation: 1830

Match everything beginning with the first ( and then backtrack to the last occurrence of ):

\(.*\)

Note: The * must be greedy for this to work. So make sure the ungreedy modifier U is not set (default).


If your strings can contain multiple occurrences of independent parenthesized substrings, i.e. "Hello (my name is) Frank (nicer (guy) thank you)", then you need a recursive pattern.

The example \(((?>[^()]+)|(?R))*\) there works quite well.

Upvotes: 2

Daniel Galecki
Daniel Galecki

Reputation: 81

Here's the code for you:

<?php
  $in = '"Hello my name is Frank (nicer guy)"';
  $out = preg_replace('/\s\(.*\)/','',$in);
  echo $out;
?>

Output will be: "Hello my name is Frank"

Upvotes: 0

Related Questions