从字符串中获取所有 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>';

要使用正则表达式匹配调用函数,您可以使用函数preg_replace_callback http://php.net/manual/en/function.preg-replace-callback.php。 像这样:

function modify_href( $matches ) {
return $matches[1] . '/modified';
}
$result = preg_replace_callback('/(https?://([-w.]+)+(:d+)?(/([w/_.]*(?S+)?)?)?)/', 'modify_href', $string);

我还没有测试过这个,但我认为它应该有效。我从这里得到了正则表达式:https://rushi.wordpress.com/2008/04/14/simple-regex-for-matching-urls/

没有关于您需要的进一步信息,这是一种方法。

$string = '<div>
<a href="'.modify_href('http://somelink').'" class="possible-class">text</a>
<a href="'.modify_href('http://anotherlink').'">other text</a>
</div>';
function modify_href( $href ) {
return $href . '/modified';
}
echo $string;

不建议使用正则表达式解析 html。

您可以使用 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();

演示

相关内容

最新更新