Php – Convert PHP closing tag into comment

commentsPHPregextags

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?

Best Answer

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. :)