【问题标题】:How to replace a href links in php如何替换php中的href链接
【发布时间】:2013-08-23 08:28:02
【问题描述】:

我需要用 php 文件中的一些文本替换所有 <a> href。我用过

preg_replace('#\s?<a.*/a>#', 'text', $string);

但这会将所有链接替换为相同的文本。我需要为每个链接提供不同的文本。 如何实现这一点。也可以完全获取href链接,这意味着如果我有一个包含链接&lt;a href="www.google.com"&gt;Google&lt;/a&gt;的文件,我该如何提取字符串'&lt;a href="www.google.com"&gt;Google&lt;/a&gt;'

请帮帮我。

【问题讨论】:

  • 已经解析了 DOM...
  • 使用php.net/domdocument - 其他的都是废话,真的。如果您有一些要替换的静态链接,请使用 strireplace。如果更复杂,请解析 DOM。

标签: php html


【解决方案1】:

使用 DOMDocument。

$dom = new DOMDocument;
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('a') as $node) {
    //Do your processing here
}

【讨论】:

    【解决方案2】:

    好的,既然没有关于如何以这种方式操纵 DOM 的明确答案,我想,你想操纵它:

    $foo = '<body><p> Some BS and <a href="https://www.google.com"> Link!</a></p></body>';
    $dom = new DOMDocument;
    $dom->loadHTML($foo);//parse the DOM here
    $links = $dom->getElementsByTagName('a');//get all links
    foreach($links as $link)
    {//$links is DOMNodeList instance, $link is DOMNode instance
        $replaceText = $link->nodeValue.': '.$link->getAttribute('href');//inner text: href attribute
        $replaceNode = $dom->createTextNode($replaceText);//create a DOMText instance
        $link->parentNode->replaceChild($replaceNode, $link);//replace the link with the DOMText instance
    }
    echo $dom->saveHTML();//echo the HTML after edits...
    

    这就出来了:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
    <html><body><p> Some BS and  Link!: https://www.google.com</p></body></html>
    

    从阅读the DOMDocument 手册开始,然后点击进入我在这里使用的所有方法(和相关类)。 DOMDocument API 与客户端 JS 中的 DOM API 一样,体积庞大且不是很直观,但它就是这样......
    可以使用saveXML 方法和/或some string operations... 来呼应实际的html,没有doctype。总而言之,使用此代码作为基础,以及提供的链接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2011-03-07
      • 2014-05-19
      • 2018-03-22
      • 2013-01-12
      • 1970-01-01
      • 2015-09-16
      相关资源
      最近更新 更多