preg_replace在替换中应用字符串函数(如urlencode)
问题描述:
我想解析PHP中的所有链接在PHP文件中的这种方式:替换href ='LINK'为href ='MY_DOMAIN?URL = LINK',因为LINK会是url参数,它必须是urlencoded。我试着这样做:preg_replace在替换中应用字符串函数(如urlencode)
preg_replace('/href="(.+)"/', 'href="http://'.$host.'/?url='.urlencode('${1}').'"', $html);
但“$ {1}”只是字符串文字,而不是建立在预浸网址,有什么需要我做什么,使这个代码的工作?
答
好了,回答你的问题,你有两个选择用正则表达式。
您可以将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();
答
使用'e'修饰符。
preg_replace('/href="([^"]+)"/e',"'href=\"http://'.$host.'?url='.urlencode('\\1').'\"'",$html);
嗯正则表达式和HTML ... – kennytm 2010-08-24 12:19:15
哦,上帝......我们再次去... – Buggabill 2010-08-24 12:19:46
你愿意娱乐非正则表达式的解决方案吗? – salathe 2010-08-24 12:21:31