我有一串連接在一起成爲一個包含文本和鏈接的字符串。我想查找字符串中的網址,並且希望將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**
請告訴我問題呢?
使用'preg_replace_callback':
你也可以簡化你的代碼,做這件事的一個調用的preg_replace如下。還有現有的「鏈接」工具。 – mario 2013-02-09 20:05:33