Reputation: 7925
How to Remove everything between round brackets?
I have this paragraph with multiple brackets inside.
Albert Einstein (/ˈælbərt ˈaɪnstaɪn/; {German} [ˈalbɐt ˈaɪnʃtaɪn] ( listen); 14 March 1879 – 18 April 1955) was a German-born theoretical physicist.
i tried:
$text = preg_replace("/\([^)]+\)/",' ',$text);
$text = preg_replace('/\[.*?\]/', ' ', $text);
and the output is this:
Albert Einstein ; 14 March 1879 18 April 1955) was a German born theoretical physicist.
i want to remove everything inside and output this.
Albert Einstein was a German born theoretical physicist
Upvotes: 2
Views: 288
Reputation: 71598
You can use a recursive regex in PHP:
(\((?:[^()]+|(?1))+\))\s*
The first capture group has: \((?:[^()]+|(?1))+\)
Inside the parens, you have (?:[^()]+|(?1))+
, so that you have [^()]+
as first option, or (?1)
which refers to the first capture group, meaning you can have that same group inside the parens, which is the recursion part.
Then \s*
outside just to remove extra spaces if any. Might be actually better if you put one at the front as well and replace with a single space, but the ideal would be to remove any double space after the first substitution I believe.
Upvotes: 1