【发布时间】:2013-03-17 01:41:17
【问题描述】:
我使用以下内容查找 $content 中的所有 URL
$content = preg_match_all( '/(http[s]?:[^\s]*)/i', $content, $links );
但这将取决于http://www.google.com/some/path 中的http:// 部分。
我的问题是:
1 - 我怎样才能修改它以点击仅以 www 开头的链接,例如www.google.com?
2 - 主要目的是找到链接,并将它们替换为从另一个函数返回的值。我试过 preg_match_callback() ,但它不起作用(可能使用错误..
$content = preg_replace_callback(
"/(http[s]?:[^\s]*)/i",
"my_callback",
$content);
function my_callback(){
// do a lot of stuff independently of preg_replace
// adding to =.output...
return $output;
}
现在,按照我的逻辑(这可能是错误的),来自$content 的所有匹配项都将被$output 替换。我做错了什么?
(请不要使用匿名函数 - 我正在旧服务器上测试)
编辑我 - 在 cmets 之后,试图澄清更多细节
function o99_simple_parse($content){
$content = preg_replace_callback( '/(http[s]?:[^\s]*)/i', 'o99_simple_callback', $content );
return $content;
}
回调:
function o99_simple_callback($url){
// how to get the URL which is actually the match? and width ??
$url = esc_url_raw( $link );
$url_name = parse_url($url);
$url_name = $description = $url_name['host'];// get rid of http://..
$url = 'http://something' . urlencode($url) . '?w=' . $width ;
return $url; // what i really need to replace
}
【问题讨论】:
-
检查这个:stackoverflow.com/questions/1755144/…,尤其是魔术贴的回应。
-
谢谢,但它忽略了 HTTP 和 HTTPS 网址? .此外,没有关于回调的信息。基本上它是连接 2 个正则表达式,不是吗?
标签: php regex preg-replace preg-replace-callback