开发者

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 CONSULTA开发者_如何学CNTS [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);


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜