Elitmiar
Elitmiar

Reputation: 36909

preg_replace not doing what I expect

I have the following paterns in a paragraph of text and I need to replace it with nothing, so that it disappears from the paragraph.

The sendtence contains CONSULTANTS [45416,2010-05-11] I need to remove the [] and everything within these [] , not the characters within the [] could be anything

I tried the below but this only removes the []

$par = preg_replace('/[\[*\]]/','',$par);

Upvotes: 1

Views: 75

Answers (2)

Vikas
Vikas

Reputation: 8958

Roland,

What you are trying to match is:

[\[*\]]

Which is any of the '[', '*', ']' chars. What you really want is a pattern starting with '[' and ending with ']'. There can be any non-']' char in between. So the correct pattern would be:

\[[^\]]*\]

So this:

$par = preg_replace("/\[[^\]]*\]/", "", $par);

should work.

Thanks.

Upvotes: 2

codaddict
codaddict

Reputation: 455470

You can do:

$par = preg_replace('/\[.*?\]/s','',$par);

Explanation:

/    - Start delimiter
\[   - A literal [
.*?  - A non-greedy anything
\]   - A literal ]
/    - End delimiter
s    - Modifier to make . match even a newline

to make the replacement a bit faster you can do:

$par = preg_replace('/\[[^\]]*\]/s','',$par);

Explanation:

/    - Start delimiter
\[   - A literal [
 [   - Start of character class
 ^   - Char class negator
 ]   - End of character class
\]   - A literal ]
/    - End delimiter

Upvotes: 6

Related Questions