php - 从字符串中获取所有href,然后通过另一种方法替换
问题描述
假设您有一个从 ajax 调用中获得的动态字符串。例如,这是一个响应:
$string = '<div>
<a href="http://somelink" class="possible-class">text</a>
<a href="http://anotherlink">other text</a>
</div>';
如何将字符串中的所有 href url 修改为其他方法的结果,例如此示例方法:
function modify_href( $href ) {
return $href . '/modified';
}
所以结果字符串是:
$string = '<div>
<a href="http://somelink/modified" class="possible-class">text</a>
<a href="http://anotherlink/modified">other text</a>
</div>';
解决方案
您可以使用DomDocument和createDocumentFragment
function modify_href( $href ) {
return $href . '/modified';
}
$string = '<div>
<a href="http://somelink" class="possible-class">text</a>
<a href="http://anotherlink">other text</a>
</div>';
$doc = new DomDocument();
$fragment = $doc->createDocumentFragment();
$fragment->appendXML($string);
$doc->appendChild($fragment);
$xpath = new DOMXPath($doc);
$elements = $xpath->query("//div/a");
foreach ($elements as $element) {
$element->setAttribute("href", modify_href($element->getAttribute("href")));
}
echo $doc->saveHTML();
推荐阅读
- angular - Angular6如何测试一系列http请求
- scala - 按数组列过滤 Scala 数据帧
- windows - Symfony 警告:DOMElement::setAttribute(): string is not in UTF-8
- c - LIBC_PROBE 宏在 Glibc 中是如何实际工作的?
- asp.net-mvc - 如何使响应式网站中sitecore的html缓存无效?
- c++ - tensorflow c++ 中是否有与 tf.convert_to_tensor 等价的东西?
- python - 如果索引大于 x,则删除数据框行
- c# - ReceiveAsync 中断/中断消息传递
- sql - 根据值是否存在更新值
- firebase - 如何为第三方提供 Firebase 身份验证接口?