2014-05-21 39 views
0

我需要在php中提取文本正文中的所有鏈接並使其可點擊。問題是我似乎無法以任何方式簡化鏈接的文本。在PHP中創建和簡化文本正文的鏈接

我嘗試使用preg_replace_callback但我似乎無法得到修整功能正常工作:

function trimUrl($url){ 
    $maxLength = 3; 
    if(strlen($url)>$maxLength){ 
     $urlShort = substr($str,0,$maxLength).'...'; 
    } 
    else{ 
     $urlShort = $url; 
    } 
    return $urlShort; 
} 

function enableLinks($text){ 
    return preg_replace_callback("!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()[email protected]:%_+.~#?&;//=]+)!i", "<a href='$1' target='_blank'>".trimUrl("$1")."</a>", $text); 
} 

enableLinks("Visit more work at http://www.google.com"); 

我怎樣才能運行修剪輸出文本的preg_replace_callback中的第二功能?

回答

0

如果您在該功能中使用了一個函數,該怎麼辦?所以如果第一個函數的計算結果爲true,那麼運行這個下一個函數?並且還可以嘗試使用preg_replace_callback作爲可變格式,以便更容易地使用

0

首先,您使用的是substring()。你在哪裏定義了變量$ str?而且,如果你這樣做:

$var = preg_replace_callback("!(((f|ht)tp(s)?://)[-a-zA-Zа-яА-Я()[email protected]:%_+.~#?&;//=]+)!i", "<a href='$1' target='_blank'>".trimUrl("$1")."</a>", $text); 

比你可以使用一個新的功能:

return function($var); 
0

結束了使用更擴展功能來實現這一目標,適用於有或無「HTTP多個網址: //「:

 function trimUrlOutput($url){ 
     $maxLength = 30; 
     if(strlen($url)>$maxLength){ 
      $urlShort = substr($url,0,$maxLength).'...'; 
     } 
     else{ 
      $urlShort = $url; 
     } 
     return $urlShort; 
    } 

    function enableLinks($text){ 
     $text = ereg_replace("www\.", "http://www.", $text); 
     $text = ereg_replace("http://http://www\.", "http://www.", $text); 
     $text = ereg_replace("https://http://www\.", "https://www.", $text); 
     $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; 
     if(preg_match_all($reg_exUrl, $text, $url)) { 
      $matches = array_unique($url[0]); 
      foreach($matches as $match) { 
       $linkText = trimUrlOutput($match); 
       $replacement = "<a href=".$match." target='_blank'>{$linkText}</a>"; 
       $text = str_replace($match,$replacement,$text); 
      } 
      return $text; 
     } 
     else{ 
      return $text; 
     } 
    } 

    enableLinks("Visit more work at http://www.google.com"); 

希望這有助於某人。