PHP匹配URL并使用preg_place_allback() [英] PHP Matching URLs and using preg_replace_callback()

查看:35
本文介绍了PHP匹配URL并使用preg_place_allback()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下内容查找$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。我做错了什么?

(请不要使用匿名函数-我正在旧服务器上测试)

编辑我-在评论之后,试图用更多细节澄清

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 
    }

推荐答案

要修改已经允许www开头的URL的正则表达式,只需编写以下代码:

/((http[s]?:|www[.])[^s]*)/i
  +         ++++++++

这篇关于PHP匹配URL并使用preg_place_allback()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆