如何使用 PHP 从字符串更新所有锚点 href


how to update all anchor href from string using php

我必须使用 php 更新字符串中的所有 href 标签。前任:

<a href="test.com">test</a> lorum <a href="ola.com">ipsum</a>
so i want to change href as <a href="http://ourdomain.com?url=test.com">test</a>
lorum <a href="http://ourdomain.com?url=ola.com">ipsum</a>

请告诉我如何更新所有锚 HREF

在这里我这样做但未正确更新

$replaceStr  = "http://affilate.domain.com?cam=1&url=";
$html="<a href="test.com">test</a> lorum <a href="ola.com">ipsum</a>";
$match = array();
$url   = preg_match_all('/<a [^>]*href="(.+)"/', $html, $match);
if(count($match))
{
for($j=0; $j<count($match); $j++)
{
$html = str_replace($match[1][$j], $replaceStr.urlencode($match[1][$j]), $html);
}
}
(?<=href=")([^"]*)

试试这个。替换为 http://ourdomain.com?url=$1 。请参阅演示。

https://www.regex101.com/r/bC8aZ4/11

$re = "/(?<=href='")([^'"]*)/im";
$str = "<a href='"test.com'">test</a> lorum <a href='"ola.com'">ipsum</a>";
$subst = "http://ourdomain.com?url=$1";
$result = preg_replace($re, $subst, $str);