【问题标题】:preg_replace apply string function (like urlencode) in replacementpreg_replace 在替换中应用字符串函数(如 urlencode)
【发布时间】:2010-08-24 22:22:56
【问题描述】:

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

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

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

【问题讨论】:

  • 天哪……我们又来了……
  • 您愿意接受非正则表达式解决方案吗?

标签: php preg-replace


【解决方案1】:

好吧,要回答您的问题,Regex 有两种选择。

您可以将e modifier 用于正则表达式,它告诉preg_replace 替换是php 代码并且应该被执行。这通常被认为不是很好,因为它实际上并不比 eval 好......

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

另一个选项(恕我直言更好)是使用preg_replace_callback

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

但也不要忘记,don't parse HTML with regex...

所以在实践中,更好的方法(更健壮的方法)是:

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

【讨论】:

  • 只是 $aElement->setAttribute($href);必须在 $aElement->setAttribute('href', $href); 上替换;
【解决方案2】:

使用“e”修饰符。

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

http://uk.php.net/preg-replace - 示例 #4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 2021-06-14
    • 1970-01-01
    相关资源
    最近更新 更多