How to Remove Text Between brackets with php


How to Remove Text Between brackets with php



How to remove text Between brackets.
For exp.


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

i want to get as
$str = 'Aylmers, Ancaster';





Possible duplicate of Remove Text Between Parentheses PHP
– billynoah
14 mins ago




3 Answers
3



Please try this:


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



output:


Aylmers, Ancaster



Regex





unfortunately this does not remove nested brackets such as A (B (C) D) and leaves you with A D
– rawathemant
13 mins ago





For nested brackets we need to modify regix but I have created for current requirement.
– Gufran Hasan
11 mins ago






FYI - Those are not brackets. They are parentheses. Brackets look like this: [ ]
– billynoah
10 mins ago





@billynoah, thanks, Parenthesis "()", curly brackets "{}", square brackets ""
– Gufran Hasan
9 mins ago





ok, well then maybe that's a difference in dialect - in America anyway it's typically: Parentheses (), Brackets , Braces {}
– billynoah
8 mins ago


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



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






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?