繁体   English   中英

php将文字插入href

[英]php insert text into a href

我正在使用htmlpurifier创建网站的纯文本版本。 我现在需要将所有a href替换为纯文本网址,即“ www.example.com/aboutus”变为“ www.example.com/text/aboutus”

最初,我在域上尝试了一个简单的str_replace(我对该域使用了全局变量),但是问题是文件的链接也被替换了,即'www.example.com/document.pdf'变成了'www.example.com/ text / document.pdf”,因此失败。

是否可以使用正则表达式在其中URL不包含字符串的情况下用domain / text替换domain?

感谢您的指导,您也许可以给我:)

使用否定的前瞻

$output = preg_replace(
             '#www.example.com(?!/text/)#', 
             'www.example.com/text', 
             $input
          );

更好的是,将DOM与它一起使用:

$html = '<a href="www.example.com/something">foo</a>
         <p>hello</p>
         <a href="www.example.com/text/documents">bar</a>';

libxml_use_internal_errors(true); // supresses DOM errors

$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$hrefs = $xpath->query('//a/@href');
foreach ($hrefs as $href) {
    $href->value = preg_replace(
                      '#^www.example.com(?!/text/)(.*?)(?<!\.pdf)$#', 
                      'www.example.com/text\\1', 
                      $href->value
                   );
}

这应该给您:

<a href="www.example.com/text/something">foo</a>
<p>hello</p>
<a href="www.example.com/text/documents">bar</a>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM