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

あなたのコードは少し混乱しています:

  1. 逆方向に検索している文字列があります。を使用するsubstr()と、である必要がありますhaystack, start position, length
  2. "<!--"(の代わりに)間違った開始タグを検索していて、引数リストでのそれらの位置が(本来のように見えるのではなく)-->本来あるべき位置から逆になっています。start, lengthlast, 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 に答える
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);

?

または、<!---->、およびクリーンな文字列が必要ない場合は、次のようにします。

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