Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP REGEX delete brackets and text in brackets

Tags:

regex

php

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
like image 918
Brock Avatar asked Dec 06 '25 03:12

Brock


2 Answers

/\([^()]*\)/
  • \( - 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

like image 187
ndnenkov Avatar answered Dec 07 '25 20:12

ndnenkov


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.

like image 43
npinti Avatar answered Dec 07 '25 18:12

npinti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!