【问题标题】:Find all hrefs in page and replace with link maintaining previous link - PHP查找页面中的所有href并替换为维护先前链接的链接 - PHP
【发布时间】:2012-06-29 10:29:34
【问题描述】:

我正在尝试查找网页上的所有 href 链接并将链接替换为我自己的代理链接。

例如

<a href="http://www.google.com">Google</a>

需要

<a href="http://www.example.com/?loadpage=http://www.google.com">Google</a>

【问题讨论】:

    标签: php hyperlink text-processing


    【解决方案1】:

    使用PHP的DomDocument解析页面

    $doc = new DOMDocument();
    
    // load the string into the DOM (this is your page's HTML), see below for more info
    $doc->loadHTML('<a href="http://www.google.com">Google</a>');
    
    //Loop through each <a> tag in the dom and change the href property
    foreach($doc->getElementsByTagName('a') as $anchor) {
        $link = $anchor->getAttribute('href');
        $link = 'http://www.example.com/?loadpage='.urlencode($link);
        $anchor->setAttribute('href', $link);
    }
    echo $doc->saveHTML();
    

    在这里查看:http://codepad.org/9enqx3Rv

    如果您没有将HTML作为字符串,您可以使用cUrl(docs)来抓取HTML,也可以使用DomDocumentloadHTMLFile方法

    文档

    【讨论】:

    • 谢谢!我最终不得不这样做,因为您无法在 iframe 中访问属性“src”的动态值。
    【解决方案2】:

    我能想到的最简单的方法:

    $loader = "http://www.example.com?loadpage=";
    $page_contents = str_ireplace(array('href="', "href='"), array('href="'.$loader, "href='".$loader), $page_contents);
    

    但这可能会对包含 ?要么 &。或者如果文档的文本(不是代码)包含 href="

    【讨论】:

    • 这就是为什么您不对 HTML 使用 RegEx 或将 HTML 视为字符串的原因
    【解决方案3】:

    如果您希望将链接替换为 jQuery,您还可以执行以下操作:

    $(document).find('a').each(function(key, element){
       curValue = element.attr('href');
       element.attr('href', 'http://www.example.com?loadpage='+curValue);
    
    });
    

    但是更安全的方法是在 php offcourse 中进行。

    【讨论】:

      猜你喜欢
      • 2013-01-12
      • 1970-01-01
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-12
      • 1970-01-01
      相关资源
      最近更新 更多