2013-03-27 127 views
1

我用下面找到$内容PHP匹配的网址,并使用preg_replace_callback()

$content = preg_match_all('/(http[s]?:[^\s]*)/i', $content, $links); 

内的所有URL's但是,这将在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_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 
    } 
+0

检查内容:HTTP://计算器。 com/questions/1755144/how-to-validate-domain-name-in-php,特别是velcrow的回应。 – Gael 2013-03-27 02:41:36

+0

谢谢,但它忽略了HTTP和HTTPS url? 。此外,还没有关于回调的信息。基本上它连接了2个正则表达式,不是吗? – 2013-03-27 02:45:31

回答

2

要修改已经允许与www开头的URL正则表达式,你只需这样写:

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

谢谢!我会检查一下..回调的第二部分呢?我用错了吗? – 2013-03-27 03:07:29

+0

我不确定,因为你没有包含你的代码。 'my_callback'应该接受一个参数,像这样:'my_callback($ matches)',并且你可以使用'$ matches'中的项来构造你的输出。 – 2013-03-27 03:15:12

+0

看到我的编辑我... – 2013-03-27 03:22:45