Convert PHP closing tag into comment

v1n_vampire picture v1n_vampire · Mar 5, 2013 · Viewed 7.1k times · Source

One of the lines in my script contains a PHP closing tag inside a string. Under normal operation this does not cause a problem, but I need to comment out the line.

I have tried to comment out this line with //, /* */ and # but none of them work, the parser considers closing tag to be an actual closing tag.

Here is the line in question:

$string = preg_replace('#<br\s*/?>(?:\s*<br\s*/?>)+#i', '<br />', $string);
//                              ^^             ^^

What can I do to comment out the above line?

Answer

ppeterka picture ppeterka · Mar 5, 2013

Use a trick: concatenate the string from two pieces. This way, the closing tag is cut in two, and is not a valid closing tag anymore. '?>' --> '?'.'>'

In your code:

$string = preg_replace('#<br\s*/?'.'>(?:\s*<br\s*/?'.'>)+#i', '<br />', $string);

This will make // comments work.

For /* */ comments to work, you'd have to split the */ sequence too:

$string = preg_replace('#<br\s*'.'/?'.'>(?:\s*<br\s*'.'/?'.'>)+#i', '<br />', $string);

Remember, sometimes, even though the whole is more than the sum of its parts - but being greedy is bad, there are times you are better left with less. :)