How To Remove Anything Outside Square Brackets

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
shehabic
Forum Newbie
Posts: 2
Joined: Tue May 01, 2007 9:08 pm

How To Remove Anything Outside Square Brackets

Post by shehabic »

hello

I Need A Sysntax On How To Remove what's Outside Square Brackets :
e.g if my String is

Code: Select all

$X='blablablablablabla[TEST_1]blablablablabla[TEST_2_TEST]blablab123445!$%$#^&^&$*_#$()SGJBLABLAlabla[TEST_3_ANYTHING_3]';

I Want It to Be : 

' [TEST_1] [TEST_2_TEST] [TEST_3_ANYTHING_3] '
The Following Code Is Exactly The Inverse Of What I Want :

Code: Select all

preg_replace('/\[\w[^\]]*\]/s',' ',$X);
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Why not use preg_match_all() to find all the parts in brackets?
shehabic
Forum Newbie
Posts: 2
Joined: Tue May 01, 2007 9:08 pm

Post by shehabic »

Thanks A Lot ,
How Comes I Didn't Think About This . .

I Used This And It Worked

Code: Select all

preg_match_all('/\[\w[^\]]*\]/s',$X,$FINAL);
echo implode(",",$FINAL[0]);
Anyway I Still Wanna Know It Just For Knowledge (If Anyone Knows How To Do What I Asked For) In The 1st Post
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post by stereofrog »

Code: Select all

preg_replace('/(^|\]).*?($|\[)/', '', $X);
If possible, please use proper spelling.
Post Reply