我正在尝试在html中找到内部链接,例如
<p>This is first <a href="/old-link-first">old link</a> and this is second <a href="/old-link-second">old link</a></p>
我必须匹配相对链接对数据库进行查询才能从数据库中获取链接,我在匹配时遇到问题:/和执行。
我尝试过这个,但它似乎仅适用于第一个链接:
$out='<p>This is first <a href="/old-link-first">old link</a> and this is second <a href="/old-link-second">old link</a></p>';
$pattern = '/href="'/(.*)?"/';
function ch($match){
$oldurl = 'href="'.$match[1].'"';
// query to database
return $newurl;
}
$out = preg_replace_callback($pattern, 'ch', $out);
print $out;
可能我有很多错误提前致谢
好吧,
我没有用preg_replace_callback
做太多工作,但我想它只做一个匹配,所以你可以做的是调用一个函数并在该函数中使用preg_replace_callback,这样它就会循环直到所有内容都被替换,正如 php 文档中的第三个示例所示。
像这样的东西可能是:
<?PHP
$out='<p>This is first <a href="/old-link-first">old link</a> and this is second <a href="/old-link-second">old link</a></p>';
function ch($match){
$pattern = '/href="'/(.*)?"/';
if(is_array($match)){
$match = 'href="'.$match[1].'"';
}
// query to database
return preg_replace_callback($pattern, 'ch', $match);
}
$out = ch($out);
print $out;