0

I have this code:

$str = '(Test)';
$final = preg_replace('/\[translate=([a-z]{2})(.*)\]'.preg_quote($matches[3][$i]).'\[\/translate(.*)\]/',$str,$final,-1,$ct);

It handles 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?

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the non-greedy switch or [^\]]* instead of .* which would match "anything until ]".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.