Consider the following PHP function:
function show_html_comment($comment)
{
echo '<!-- ' . $comment . ' -->';
}
This function displays HTML comments.
But what if inside $comment
there is an HTML comment?
$comment = '<!-- foo -->';
The result of the function would be:
<!-- <!-- foo --> -->
And I do not want that. Nor should I show a modified version of the string (for example using htmlspecialchars()). I have to display the string as it is within an HTML comment.
Can anyone come up with a solution?
2
Answers
I post here what I have investigated:
An initial solution could be to replace the < !-- and --> tokens with [!-- --] or {!-- --} or something similar.
Another possible solution is to insert blanks inside the tokens.
Another solution could be to replace some characters in the tokens with similar Unicode characters. For example, use the hyphen character U+2010 instead of the character U+002D, or replace the < > characters with similar ones. For example, you could put comments like:
< !-- ≺!-- ≺!-- foo --≻ --≻ -->
Here are the similar characters I have found so far:
Another solution could be to insert invisible characters inside the tokens to "break the tokens" so that the browser does not detect them as HTML comments. It occurs to me to use for example the character U+200E.
For instance:
If you run the following code, you will have a file with an HTML comment inside another HTML comment, and the browser will not detect it:
You can use htmlspecialchars as @vee mention in the comment or instead if you are pretty sure about structure of your string you can use str_replace like: