2

So i have a string with flags like this: <<-- name -->> and now I want to replace all of them for ''.

I made the following function:

function removeFlags($output) {
    $output = preg_replace('/\<<--[^-->>]+-->>/', '', $output);
    return $output;
}

It works fine for the most flags but not when they contain numbers. For example: <<-- Model -->> will just be replaced for '', but <<-- 360 -->> will not be removed.

What am I doing wrong?

3 Answers 3

2

This should work for you, as you want to replace anything that is preceded and succeeded by a certain pattern

$output = preg_replace('/\<<--.+?-->>/', '', $output);

And I think your pattern should have worked for numbers as well, but do the numbers have a space before and after them?

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. It does indeed.
It has a space before it or a _
1

The hyphen - inside a character class indicates a range. You are accidentally negating a range from - to > which contains digits 0-9 so it can not match <<-- 360 -->>

enter image description here

To match a hyphen literally, put it at start or end of the class or escape it with a backslash.
Also you need to add only one of the different characters to the character class.

<<--[^>-]+-->>

See demo at regex101

3 Comments

@LarsVelthuis That's no reason why I should not point out the problem : )
Thanks. It gives me a better understanding of how preg_replace works.
@LarsVelthuis I find this answer very helpful and as bobble bubble writes it points out the root of the problem why the pattern did not work.
1

This pattern works:

$output = preg_replace('/\<<--[^.]+-->>/', '', $output);

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.