【问题标题】:Extract all urls Href php提取所有网址 Href php
【发布时间】:2011-07-12 22:17:44
【问题描述】:

如何将这些链接转换为 sha1?然后返回到已经用sha1应用的html


$dom = new DOMDocument;
$dom->loadHTML($html);
$links = $dom->getElementsByTagName('a');
foreach ($links as $link) {
    if (preg_match("/globo.com/i", $link->getAttribute('href'))) {
        $v = $link->getAttribute('href');
        $str = str_replace($v,'http://www.globo.com/?id='.sha1($v),$v);
        $str2 = str_replace($v,$str,$html);
        echo $str2."
"; } }

【问题讨论】:

  • 所以您正在尝试用新的网址更新现有网址?
  • 请注意,preg_match('/something/i', $text) 比简单的 stripos($text, 'something') !== false 慢得多,后者在您的情况下完全可以正常工作。

标签: php dom href


【解决方案1】:

您可以将href 放回元素中:

$dom = new DOMDocument;
$dom->loadHTML($html);
$links = $dom->getElementsByTagName('a');

foreach ($links as $link) {
    $href = $link->getAttribute('href');
    if (preg_match("/globo.com/i", $href)) {
        $newHref = 'http://www.globo.com/?id=' . sha1($v);
        $link->setAttribute('href', $newHref);
    }
}

然后使用saveHTML()导出完成的HTML。

echo $dom->saveHTML();

【讨论】:

    猜你喜欢
    • 2011-07-12
    • 2018-03-22
    • 1970-01-01
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    • 1970-01-01
    相关资源
    最近更新 更多