Regex issue using preg_replace
I have this code:
$str = '(Test)';
$final = preg_replace('/\[translate=([a-z]{2})(.*)\]'.preg_quote($matches[3][$i]).'\[\/translate(.*)\]/',$str,$final,-1,$ct);
It ha开发者_开发技巧ndles a situation like this okay:
test0[translate=en]Hello![/translate]test1
Which comes out as:
test0(Test)test1
But in this situation:
[quote:3ggw49so][translate=en]Hello![/translate][/quote:3ggw49so]
It comes out as:
[quote:3ggw49so](Test)
$matches[3][$i] is "Hello!" in this case and $str is "(Test)", and final is the full string that gets overwritten. So it's removing the [/quote:3ggw49so] part, why is that?
The *
is a greedy quantifier, which means that it matches as much as possible. Your .*
matches all the way to the last ]
. To make a quantifier non-greedy, append a question mark: .*?
.
$final = preg_replace('/\[translate=([a-z]{2})(.*?)\]'.preg_quote($matches[3][$i]).'\[\/translate(.*?)\]/',$str,$final,-1,$ct);
You can use the non-greedy switch or [^\]]*
instead of .*
which would match "anything until ]".
精彩评论