-1

How to remove text Between brackets. For exp.

$str = 'Aylmers(test, test2), Ancaster(Clandeboye, Bluevale)';

i want to get as
$str = 'Aylmers, Ancaster';
Sandeep Sherpur
  • 2,418
  • 25
  • 27
  • For nested brackets you can check out my answer https://stackoverflow.com/questions/51278345/how-to-remove-text-between-brackets-with-php/51278504#51278504 – Rajat Jain Jul 11 '18 at 06:32

3 Answers3

6

Try this:

$str = 'Aylmers(test, test2), Ancaster(Clandeboye, Bluevale)';
echo preg_replace("/\([^)]+\)/","",$str );

output:

Aylmers, Ancaster

Regex

Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51
0

This should do it:

`<?php`
`$string = "Stay 01 (Remove 01), Stay 02 (Remove 02)";`
`echo preg_replace("/\([^)]+\)/","",$string); // 'ABC '`
0

If also want to remove nested data in brackets. You can use:

$str = 'Aylmers(test, test2), Ancaster(Clandeboye, Bluevale)';
echo preg_replace("/\(([^()]*+|(?R))*\)/","", $str);

//output:
//Aylmers, Ancaster

Explanation:

/ - Opening delimiter

( - Match opening parenthesis

[^)]+ - Match character that is not a closing parenthesis

) - Match closing parenthesis

/ - Closing delimiter

Community
  • 1
  • 1
Rajat Jain
  • 1,339
  • 2
  • 16
  • 29
  • It's nice that you added some explanation, but if you're going to explain, then explain why/how it matches nested parenthesis, rather than just a single pair. Having such an explanation would make this actually better than the [effectively identical code in an answer on the dup-target](https://stackoverflow.com/a/31788152/3773011). – Makyen Jul 11 '18 at 07:13