简体   繁体   English

PHP:显示 HTML 评论

[英]PHP: show HTML comments

Consider the following PHP function:考虑以下 PHP function:

function show_html_comment($comment)
{
   echo '<!-- ' . $comment . ' -->';
}

This function displays HTML comments.此 function 显示 HTML 注释。

But what if inside $comment there is an HTML comment?但是如果在$comment里面有一个 HTML 评论呢?

$comment = '<!-- foo -->';

The result of the function would be: function 的结果将是:

<!-- <!-- foo --> -->

And I do not want that.我不希望那样。 Nor should I show a modified version of the string (for example using htmlspecialchars()).我也不应该显示字符串的修改版本(例如使用 htmlspecialchars())。 I have to display the string as it is within an HTML comment.我必须在 HTML 注释中显示字符串。

Can anyone come up with a solution?任何人都可以提出解决方案吗?

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:您可以使用htmlspecialchars作为评论中提到的@vee,或者如果您非常确定字符串的结构,您可以使用str_replace ,例如:

function show_html_comment($comment)
{
    $comment = str_replace('<!--', '', $comment);
    $comment = str_replace('-->', '', $comment);
    echo '<!-- ' . trim($comment) . ' -->';
}

show_html_comment('<!-- foo -->'); // <!--  foo  -->

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.另一种解决方案可能是用类似的 Unicode 字符替换令牌中的某些字符。 For example, use the hyphen character U+2010 instead of the character U+002D, or replace the < > characters with similar ones.例如,使用连字符 U+2010 代替字符 U+002D,或将 < > 字符替换为类似字符。 For example, you could put comments like:例如,您可以发表如下评论:

< !-- ≺!-- ≺!-- foo --≻ --≻ --> < !-- ≺!-- ≺!-- 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.另一种解决方案可能是在标记内插入不可见字符以“破坏标记”,以便浏览器不会将它们检测为 HTML 注释。 It occurs to me to use for example the character U+200E.例如,我想到使用字符 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:如果您运行以下代码,您将在另一个 HTML 注释中拥有一个带有 HTML 注释的文件,并且浏览器不会检测到它:

file_put_contents('test.html', '<!DOCTYPE html><html><body><!-- <' . "\u{200e}" . '!-- foo --' . "\u{200e}" . '> --></body></html>');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM