Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

php - How to remove square brackets and anything between them with a regex?

How can I remove text from between square brackets and the brackets themselves?

For example, I need:

hello [quote="im sneaky"] world

to become:

hello world

Here's what I'm trying to use, but it's not doing the trick:

preg_replace("/[[(.)]]/", '', $str);

I just ended up with:

hello quote="im sneaky" world
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

[ and ] are special characters in a regex. They are used to list characters of a match. [a-z] matches any lowercase letter between a and z. [03b] matches a "0", "3", or "b". To match the characters [ and ], you have to escape them with a preceding .

Your code currently says "replace any character of [](). with an empty string" (reordered from the order in which you typed them for clarity).


Greedy match:

preg_replace('/[.*]/', '', $str); // Replace from one [ to the last ]

A greedy match could match multiple [s and ]s. That expression would take an example [of "sneaky"] text [with more "sneaky"] here and turn it into an example here.

Perl has a syntax for a non-greedy match (you most likely don't want to be greedy):

preg_replace('/[.*?]/', '', $str);

Non-greedy matches try to catch as few characters as possible. Using the same example: an example [of "sneaky"] text [with more "sneaky"] here becomes an example text here.


Only up to the first following ]:

preg_replace('/[[^]]*]/', '', $str); // Find a [, look for non-] characters, and then a ]

This is more explicit, but harder to read. Using the same example text, you'd get the output of the non-greedy expression.


Note that none of these deal explicitly with white space. The spaces on either side of [ and ] will remain.

Also note that all of these can fail for malformed input. Multiple [s and ]s without matches could cause a surprising result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...