首页 > 解决方案 > 从字符串中获取所有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>';

标签: phppreg-replace

解决方案


建议使用 regex 解析 html

您可以使用DomDocumentcreateDocumentFragment

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();

演示


推荐阅读