javascript - 在每个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
解决方案
永远不要犯像文本一样解析 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();
推荐阅读
- c# - 是否有一种通用方法可以在现有列表上创建“视图”,允许仅在调用提交方法后才进行更改?
- c++ - 为什么我无法在下面的代码中为浮点变量添加值?
- pytorch - 如何在 pytorch 上加载预批处理数据集
- git - 有没有办法获取分支的基本分支名称?
- python - Selenium 无法在 Jupyter 中加载,但可以在 Python3 的控制台和 Sublime Text 中使用
- javascript - 如何检查 Javascript 中问题的答案?
- amazon-web-services - 如何将 .RData 文件加载到 AWS sagemaker 笔记本?
- python - 使用python一次更改文本文件的内容
- python - 尽管阅读了文档,但 PostgreSQL UPDATE 语句错误
- optimization - 优化具有非线性约束的线性目标函数的最可靠方法是什么?为什么?