Php preg_replace在replace中应用字符串函数(如urlencode)

Php preg_replace在replace中应用字符串函数(如urlencode),php,preg-replace,Php,Preg Replace,我想以如下方式解析php中html文档字符串中的所有链接:将href='LINK'替换为href='MY_DOMAIN?URL=LINK',因此,因为链接将是URL参数,所以它必须是URL编码的。我正试图这样做: preg_replace('/href="(.+)"/', 'href="http://'.$host.'/?url='.urlencode('${1}').'"', $html); 但是“${1}”只是字符串文字,不是在preg url中建立的,我需要做什么才能使代码正常工作?使用

我想以如下方式解析php中html文档字符串中的所有链接:将href='LINK'替换为href='MY_DOMAIN?URL=LINK',因此,因为链接将是URL参数,所以它必须是URL编码的。我正试图这样做:

preg_replace('/href="(.+)"/', 'href="http://'.$host.'/?url='.urlencode('${1}').'"', $html);
但是“${1}”只是字符串文字,不是在preg url中建立的,我需要做什么才能使代码正常工作?

使用“e”修饰符

preg_replace('/href="([^"]+)"/e',"'href=\"http://'.$host.'?url='.urlencode('\\1').'\"'",$html);
-示例4使用“e”修饰符

preg_replace('/href="([^"]+)"/e',"'href=\"http://'.$host.'?url='.urlencode('\\1').'\"'",$html);

-示例4

好吧,要回答您的问题,您有两个选择

您可以使用到regex的,它告诉preg_replace替换是php代码,应该执行。这通常被认为是不好的,因为它实际上并不比评估好

preg_replace($regex, "'href=\"http://{$host}?url='.urlencode('\\1').'\"'", $html);
IMHO更好的另一个选项是使用:

但也永远不会忘记

因此,在实践中,更好、更稳健的方法是:

$dom = new DomDocument();
$dom->loadHtml($html);
$aTags = $dom->getElementsByTagName('a');
foreach ($aTags as $aElement) {
    $href = $aElement->getAttribute('href');
    $href = 'http://'.$host.'?url='.urlencode($href);
    $aElement->setAttribute('href', $href);
}
$html = $dom->saveHtml();

好吧,为了回答你的问题,你有两个选择

您可以使用到regex的,它告诉preg_replace替换是php代码,应该执行。这通常被认为是不好的,因为它实际上并不比评估好

preg_replace($regex, "'href=\"http://{$host}?url='.urlencode('\\1').'\"'", $html);
IMHO更好的另一个选项是使用:

但也永远不会忘记

因此,在实践中,更好、更稳健的方法是:

$dom = new DomDocument();
$dom->loadHtml($html);
$aTags = $dom->getElementsByTagName('a');
foreach ($aTags as $aElement) {
    $href = $aElement->getAttribute('href');
    $href = 'http://'.$host.'?url='.urlencode($href);
    $aElement->setAttribute('href', $href);
}
$html = $dom->saveHtml();

哦,上帝。。。我们又来了…你愿意接受非正则表达式的解决方案吗?天啊。。。我们又来了…您愿意接受非正则表达式解决方案吗?只需$AEElement->setAttribute$href;必须在$AELENT->setAttribute'href',$href;只需$AELENT->setAttribute$href;必须在$AELENT->setAttribute'href',$href;