2013-02-09 34 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