保存HTML注释的内容


Save content of an HTML comment

我有一个页面,我想保存一个html评论的评论作为一个变量:

<!--http://localhost/sfddsf.png-->

我如何只得到html评论的内容?我搜索了几个答案,但它不起作用。

function getCurrentUrl(){
    $domain = $_SERVER['HTTP_HOST'];
    $url = "http://" . $domain . $_SERVER['REQUEST_URI'];
    return $url;
}
$html = getCurrentUrl();
$content = substr($html, strpos($html, "-->"), strpos($html, "<--"));
print_r( $content);

我知道很多人不喜欢正则表达式,但它们在这里可能会派上用场。试试这样写:

    $html = '<!--http://localhost/sfddsf.png-->';
    preg_match('/<!--(['S]+)-->/', $html, $matches);
    if ($matches[1])
       $url = $matches[1]; // should be http://localhost/sfddsf.png

好运。

你的代码有点混乱:

  1. 你有你正在反向搜索的字符串;使用substr()时,应该是haystack, start position, length
  2. 你正在寻找错误的开始标签("<!--"而不是-->),并且它们在参数列表中的位置与它应该是(start, length而不是last, first,因为它看起来你有)相反。
  3. 你没有搜索任何东西,甚至接近一个html标签的返回值为getCurrentUrl()

下面的代码可以工作。但是,也要注意,如果在你搜索的标记中有多个html注释,这将不起作用。

<?php
$html = "
<html>
<head>
<!--http://localhost/sfddsf.png-->
</head>
<body></body>
</html>
";
echo "$html'n";
$strstart = strpos($html, "<!--") + 4;
$strend = strpos($html, "-->") - $strstart;
echo "$strstart, $strend'n";
$content = substr($html, $strstart, $strend);
print($content);
?>
http://codepad.org/3STPRsoj

打印:

<html>
<head>
<!--http://localhost/sfddsf.png-->
</head>
<body></body>
</html>
22, 27
http://localhost/sfddsf.png

应该是:

$start = strpos($html, "<!--");
$end = strpos($html, "-->") + 3;
$content = substr($html, $start, $end - $start);

?

或者,如果您不想要<!---->,以及一个干净的字符串,您可以这样做:

$start = strpos($html, "<!--") + 4;
$end = strpos($html, "-->");
$content = trim(substr($html, $start, $end - $start));

不要用regex解析html。使用xpath:

$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DomXpath($dom);
foreach($xpath->query("//comment()") as $comment){
    echo $comment->nodeValue."'n";
}