【问题标题】:change all href of external page after insert it插入后更改外部页面的所有href
【发布时间】:2016-03-28 05:31:47
【问题描述】:

我已使用 simple_html_dom.php 将外部内容插入到我的页面中,但所有 href 都不起作用:

 href='oldpage.php'

我希望将其更改为

href='http://localhost/oldpage.php'

href='http://localhost/mynewpage.php'

有没有办法将所有href更改为新href,比如在它之前添加一些字符串? 谢谢你

【问题讨论】:

  • 那么,为什么不在执行另一个脚本的同时处理它呢?对我来说听起来会更简单。
  • @Fred-ii- 脚本可以带上所有的html文本。我想将所有 href 更新为新链接,例如在其前面添加其他文本!
  • 那么为什么要添加 javascript/jquery 标签?如果您需要 PHP 解决方案,则需要删除它们,因为这意味着您正在寻找这些方法。您需要编辑您的问题,以便让问题的访问者知道您在此处想要/需要什么。
  • 可能导致问题的简单解决方案,str_replace('href="', 'href="http://www.example.com/', $string); 或使用 domdocument 并拉取所有 href 属性。

标签: javascript php jquery html


【解决方案1】:

您可以使用 .each() 来迭代您的锚标记。然后使用 .attr 应该可以得到 href 属性值。

然后使用+ 追加字符串应该可以完成工作。所以像下面这样的东西应该可以工作

$("a.links").each(function(){
    var $this = $(this);
    var currentHref = $this.attr("href");
    var modifiedHref = "your string" + currentHref;

    $this.attr("href", modifiedHref);
});

【讨论】:

    【解决方案2】:

    你可以做一个简单的字符串替换,比如:

    str_replace('href="', 'href="http://www.example.com/', $string);
    

    或使用 domdocument:

    $page = '<html><head></head><body><a href="simple"></a><h1>Hi</h1><a href="simple2"></a></body></html>';
    $doc = new DOMDocument();
    $doc->loadHTML($page);
    $as = $doc->getElementsByTagName('a');
    foreach($as as $a){
        $a->setAttribute('href', 'http://www.example.com/' . $a->getAttribute('href'));
    }
    print_r($doc->saveHTML());
    

    输出:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
    <html><head></head><body><a href="http://www.example.com/simple"></a><h1>Hi</h1><a href="http://www.example.com/simple2"></a></body></html>
    

    这不考虑绝对路径,你需要一个正则表达式方法。

    如果引用类型不同,您还需要为 str_replace 示例使用正则表达式。可以为此执行('|") 之类的操作,然后使用$1 匹配引用类型。

    【讨论】:

      【解决方案3】:

      这是使用 replace

      的纯 javascript 方法
      //replace selector 'a' with your css selector if needed
      for(var i=0;i<document.querySelectorAll('a').length;++i){
      var new_href=document.querySelectorAll('a')[i].getAttribute('href').replace(/(http:[/]{2}localhost)[/].*/ig, '$1/mynewpage.php')
      document.querySelectorAll('a')[i].setAttribute('href',new_href)
      }
      //
      

      【讨论】:

        【解决方案4】:

        你只需要添加

        <base href="http://localhost/"></base>
        

        头部内部。 它为所有其他锚标记创建基本 url。将根据需要转换 Url。

        它会为你工作。 试试看。

        【讨论】:

          【解决方案5】:

          只需在您的网址前附加“/”即可

          href='oldpage.php' => href='/oldpage.php'
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-10-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-06-29
            • 2011-05-16
            相关资源
            最近更新 更多