简体   繁体   中英

Regular Expression matching syntax

I need to replace every instance of any text in square brackets with something else, with each square bracket block being treated separately. For example, start with:

[quote author=joe link=topic=765.msg4476#msg4476 date=1330380346] This is the quoted text [/quote] This is the new post

being turned into:

** This is the quoted text ** This is the new post

I tried using the following:

preg_replace('/\[.*\]/', '**', $msgtext);

What I get is:

** This is the new post

It seems to be matching from the first '[' character to the last ']' character in the entire string, even if there are a bunch of separate blocks of square brackets in the larger text. How do I change my regex to replace each block between the square brackets individually? Obviously my .* in the regex is matching everything including right brackets until the last one, but I want it to stop at the first right bracket it encounters, and then repeat that logic throughout the entire string.

You need to use a non-greedy match, either by using the /U flag to make the whole pattern greedy:

preg_replace('/\[.*\]/U', '**', $msgtext);

or by using .*? ("zero or more, and preferably as few as possible") instead of .* ("zero or more, and preferably as many as possible"):

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

Alternatively, you can use [^\\]] ("any character except ] ") instead of . ("any character except newline"):

preg_replace('/\[[^\]]*\]/', '**', $msgtext);

默认情况下,PHP的regexp会进行贪心匹配,您需要将其设置为不贪心(例如,使用u开关)

preg_replace('/\[.*\]/U', '**', $msgtext);

这对我有用:

preg_replace('/\[[^\]]*\]/', '**', $msgtext);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM