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?
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?
This pattern works:
$output = preg_replace('/\<<--[^.]+-->>/', '', $output);
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 -->>
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.
<<--[^>-]+-->>