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

如何使用php从字符串更新所有锚href,php,regex,anchor,Php,Regex,Anchor,我必须使用php更新字符串中的所有href标记。 例: 洛伦 所以我想把href改成 洛伦 请告诉我如何更新所有anchore href 在这里,我这样做,但没有正确更新 $replaceStr = "http://affilate.domain.com?cam=1&url="; $html="<a href="test.com">test</a> lorum <a href="ola.com">ipsum</a>"; $match =

我必须使用php更新字符串中的所有href标记。 例:

洛伦 所以我想把href改成 洛伦 请告诉我如何更新所有anchore 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);
}
}
$replaceStr=”http://affilate.domain.com?cam=1&url=";
$html=“lorum”;
$match=array();
$url=preg_match_all('/]*href=“(.+)”/”,$html,$match);
如果(计数($match))
{

对于($j=0;$jI)来说,不鼓励您为此使用正则表达式,使用现有的HTML解析器(PHP对此有选项)是更安全的选择。本网站解释了为什么正则表达式不是一个好主意,并提供了更好的PHP解决方案:
$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=")([^"]*)
$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);