preg_replace应用字符串函数(如urlencode)替换

hip*_*out 1 php preg-replace

我想以这样的方式解析php中的html文档字符串中的所有链接:将href ='LINK'替换为href ='MY_DOMAIN?URL = LINK',因为LINK将是url参数,它必须是urlencoded.我正在尝试这样做:

preg_replace('/href="(.+)"/', 'href="http://'.$host.'/?url='.urlencode('${1}').'"', $html);
Run Code Online (Sandbox Code Playgroud)

但'$ {1}'只是字符串文字,不是在preg url中创建的,我需要做什么才能使这段代码正常工作?

irc*_*ell 10

那么,要回答你的问题,你有两个选择Regex.

您可以使用e修饰符来表示正则表达式,它preg_replace表示替换是php代码并且应该执行.这通常被视为不太好,因为它真的没有比eval更好......

preg_replace($regex, "'href=\"http://{$host}?url='.urlencode('\\1').'\"'", $html);
Run Code Online (Sandbox Code Playgroud)

另一种选择(更好的恕我直言)是使用preg_replace_callback:

$callback = function ($match) use ($host) {
    return 'href="http://'.$host.'?url='.urlencode($match[1]).'"';
};
preg_replace_callback($regex, $callback, $html);
Run Code Online (Sandbox Code Playgroud)

但也永远不要忘记,不用正则表达式解析HTML ...

所以在实践中,更好的方法(更强大的方式)是:

$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();
Run Code Online (Sandbox Code Playgroud)