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
/Uflag to make the whole pattern greedy:or by using
.*?(“zero or more, and preferably as few as possible”) instead of.*(“zero or more, and preferably as many as possible”):Alternatively, you can use
[^\]](“any character except]“) instead of.(“any character except newline”):