2012-05-20 31 views
4

我使用PHP中的的preg_replace功能,我試圖替換用戶提交與bit.ly縮短網址鏈接:如何使用preg_replace獲取替換的文本?

$comment = preg_replace('/(http|ftp)+(s)?:(\/\/)((\w|\.)+)(\/)?(\S+)?/i', '', $strText); 

這將只顯示註釋,「消滅」的網址。問題是如何從文本中獲取URL並在稍後添加它?從php.net

回答

3

preg_replace_callback()

實施例:

<?php 
// this text was used in 2002 
// we want to get this up to date for 2003 
$text = "April fools day is 04/01/2002\n"; 
$text.= "Last christmas was 12/24/2001\n"; 
// the callback function 
function next_year($matches) 
{ 
    // as usual: $matches[0] is the complete match 
    // $matches[1] the match for the first subpattern 
    // enclosed in '(...)' and so on 
    return $matches[1].($matches[2]+1); 
} 
echo preg_replace_callback(
      "|(\d{2}/\d{2}/)(\d{4})|", 
      "next_year", 
      $text); 

?> 

定義的回調函數,它取代了URL。它將接收匹配作爲參數,並且在內部將根據這些匹配形成替換字符串。

相關問題