Brock
Brock

Reputation: 161

PHP REGEX delete brackets and text in brackets

Need to delete brackets and text in it. For now, it almsot working. Deletes all text starting from bracket. My code:

$lines = preg_replace("/\(([^\d]+)/", '',  $lines);

For example, text:

Some random words (word1 / word2 / word3) aaaa

Code deletes all text after brackets too,

Some random words

but what I need to do is (what it should look like):

Some random words aaaa

Upvotes: 3

Views: 124

Answers (2)

ndnenkov
ndnenkov

Reputation: 36110

/\([^()]*\)/
  • \( - opening bracket
  • [^()]* - as many characters as possible, which are not brackets
  • \) - closing bracket

You can optionally remove one space at the end (/\([^()]*\) ?/) so that you wont have two spaces where the removal happened.


Note that this wont handle cases of nested brackets like:

foo (bar (baz) quiz)

To do that, you will have to be a little more creative:

(?<no_brackets>[^()]*){0}(?<balanced_brackets>\(\g<no_brackets>\)|\(\g<no_brackets>\g<balanced_brackets>\g<no_brackets>\))

See it in action

Upvotes: 3

npinti
npinti

Reputation: 52195

You are missing an extra \) at the end of your expression. As is, your expression will start matching the moment it finds an open bracket and keep on going.

Upvotes: 2

Related Questions