2013-02-09 67 views
0

我有一串連接在一起成爲一個包含文本和鏈接的字符串。我想查找字符串中的網址,並且希望將href添加到每個網址(創建鏈接)。我正在使用正則表達式模式來查找字符串中的URL(鏈接)。檢查下面我舉的例子:從一串字符串創建url鏈接

例子:

<?php 

// The Text you want to filter for urls 
     $text = "The text you want to filter goes here. http://google.com/abc/pqr 
2The text you want to filter goes here. http://google.in/abc/pqr 
3The text you want to filter goes here. http://google.org/abc/pqr 
4The text you want to filter goes here. http://www.google.de/abc/pqr"; 

// The Regular Expression filter 
     $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/"; 


// Check if there is a url in the text 
     if (preg_match($reg_exUrl, $text, $url)) { 
      // make the urls hyper links 
      echo preg_replace($reg_exUrl, "<a href='.$url[0].'>" . $url[0] . "</a> ", $text); 
     } else { 
      // if no urls in the text just return the text 
      echo $text . "<br/>"; 
     } 
     ?> 

卻是露出下面的輸出:

> The text you want to filter goes here. **http://google.com/abc/pqr** 2The 
> text you want to filter goes here. **http://google.com/abc/pqr** 3The text 
> you want to filter goes here. **http://google.com/abc/pqr** 4The text you 
> want to filter goes here. **http://google.com/abc/pqr** 

請告訴我問題呢?

+0

使用'preg_replace_callback':

你也可以簡化你的代碼,做這件事的一個調用的preg_replace如下。還有現有的「鏈接」工具。 – mario 2013-02-09 20:05:33

回答

2

由於你的正則表達式是用斜線分隔的,所以當你的正則表達式包含它們時,你需要非常小心。通常,使用不同的字符來劃分正則表達式更簡單:PHP不介意你使用的是什麼。

嘗試用另一個字符替換第一個和最後一個「/」字符,例如「#」和你的代碼可能會工作。如果你unversed與佔位符語法

<?php 

$text = 'The text you want to filter goes here. http://google.com/abc/pqr 
    2The text you want to filter goes here. http://google.in/abc/pqr 
    3The text you want to filter goes here. http://google.org/abc/pqr 
    4The text you want to filter goes here. http://www.google.de/abc/pqr'; 

echo preg_replace('#(http|https|ftp|ftps)\://[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(/\S*)?#i', '<a href="$0">$0</a>', $text); 
+0

在http://css-tricks.com/snippets/php/find-urls-in-text-make-links/的*評論*中提供了更多解決方案。博客文章中的解決方案本身也不起作用。 – 2014-08-07 15:01:38