首页 > 解决方案 > 在每个href出现之前放置文本?

问题描述

我目前正试图https://shortdomain.com/api?p=a-href-url-here.com在我的网站上的每个链接之前放置这样的东西在一个特定的 div 中。

$main = get_the_content_with_formatting();
$stripped = str_replace('<a href="http://example.net/', '<a href="https://shortdomain.com/api?p=http://example.net/', $main);

上面的方法有效,但只有当链接是那个 URL 时,它显然只会返回标准 URL。

有没有一种方法可以使用 JavaScript 或 PHP 在每个 href 的链接前面加上前缀?

这是里面内容的选择器$main

#the-post > div.post-inner > div.entry > p > strong > a

标签: javascriptphpjquery

解决方案


永远不要犯像文本一样解析 HTML 的错误;它不是!使用适当的 DOM 解析器来提取您的值,然后更改它们。

<?php
$main = "<div><p>Here is some <a href='http://example.com/'>sample</a> text.</p></div>";
$dom = new DomDocument();
$dom->loadHtml($main, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED);
foreach ($dom->getElementsByTagName("a") as $anchor) {
    $href = $anchor->getAttribute("href");
    if ($href) {
        $anchor->setAttribute("href", "https://shortdomain.com/api?p=" . urlencode($href));
    }
}
echo $dom->saveHTML();

推荐阅读