/    Sign up×
Community /Pin to ProfileBookmark

Remove everything between square brackets.

Hello,
I’m trying to remove square brackets and everything between them from a string, using regular expressions.

$string = ‘1 [any12text#!@] 2 [sfd$#12] 3’;
$string = preg_replace(‘/[(.*)]/’, ”, $string);
echo $string;

Outputs: 1 3
Instead of: 1 2 3

I understand that it replaces everything, including the inner brackets, from the first to the last brackets.
I also know that the ^ sign is used to specify something you don’t want in a patten, so it should have been something like ^[ and ^] but I couldn’t get it to work.

Any suggestions?
Thanks in advance.

to post a comment
PHP

5 Comments(s)

Copy linkTweet thisAlerts:
@TJ111Dec 17.2007 — It's because ".*" is greedy, meaning it will stay true as long as it possibly can. Change your regexp to this:

<i>
</i>/[(.*?)]/'

".*?" is non-greedy, meaning it will go until it can find a match for the next character in the expression. You may also need to pass a /g (global) flag, so it does this wherever possible.
Copy linkTweet thisAlerts:
@EdanauthorDec 17.2007 — Hey, thanks a lot!

Anyway, how exactly can I include this flag?

I'm seriously awful with regular expressions.
Copy linkTweet thisAlerts:
@TJ111Dec 17.2007 — Easy, just use:
<i>
</i>$string = preg_replace('/[(.*?)]/g', '', $string);


I used to be the same way. I'd very highly recommend you take 20-30 min and read through the tutorial over at http://www.regular-expressions.info . It really goes step by step through the reg exp engine and how it interprets each item. The 20-30 min now will save loads of time later down the road.
Copy linkTweet thisAlerts:
@EdanauthorDec 17.2007 — Fine.

Thanks again o:
Copy linkTweet thisAlerts:
@MrCoderDec 18.2007 — Would this be better?

[CODE]
$string = preg_replace('/[([^]]*)]/', '', $string);
[/CODE]
×

Success!

Help @Edan spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...