从字符串中获取所有href,然后通过另一种方法替换

时间:2018-05-22 13:28:47

标签: php preg-replace

假设你有一个来自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>';

3 个答案:

答案 0 :(得分:0)

如果没有您需要的更多信息,这就是其中之一。

$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;

答案 1 :(得分:0)

要使用正则表达式匹配调用函数,可以使用函数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/

答案 2 :(得分:0)

not recommended to parse html with regex

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

Demo