0

我有一个页面,我想将 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);
4

4 回答 4

2

我知道很多人都在使用正则表达式,但它们在这里可能会派上用场。尝试类似:

    $html = '<!--http://localhost/sfddsf.png-->';

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

祝你好运。

于 2011-12-06T23:59:48.583 回答
0

不要用正则表达式解析 html。使用 xpath:

$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DomXpath($dom);

foreach($xpath->query("//comment()") as $comment){
    echo $comment->nodeValue."\n";
}
于 2011-12-07T03:50:49.960 回答
0

不应该是:

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

?

或者,如果您不想要<!--and-->和一个干净的字符串,您可以执行以下操作:

$start = strpos($html, "<!--") + 4;
$end = strpos($html, "-->");
$content = trim(substr($html, $start, $end - $start));
于 2011-12-06T23:58:45.223 回答
0

您的代码有点混乱:

  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
于 2011-12-07T00:23:05.183 回答