2011-01-24 75 views
2

我想检查一个字符串并将原始字符串中可能为潜在链接的所有子字符串转换为http://www.google.com或www.google.com,替换为 <a href='http://www.google.com'>http://www.google.com</a>以便我可以创建真正的链接从他们。PHP url从字符串创建

我该怎么做?

+3

可能重复http://stackoverflow.com/questions/507436/how-do-i-linkify-urls-in-a-string-with-php) – alexn 2011-01-24 10:15:21

+0

@alexn:并不完美,因为亚历山大希望在没有`http://`的情况下链接到URL。 – 2011-01-24 11:45:51

+0

@Tim足够公平,然后我建议亚历山大看看这个答案的解决方案,并根据需要修改它http://stackoverflow.com/questions/1113840/php-remove-url-from-string – alexn 2011-01-24 12:17:38

回答

1

您可以创建通过调用下面的函数在PHP中的HTML链接:

$stringToCheck = 'http://www.google.com, or www.google.com'; 
$stringWithHTMLLinks = ''; 

$stringWithHTMLLinks = preg_replace('/\b((https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[A-Z0-9+&@#\/%=~_|]/si', '<a href="\0">\0</a>', $stringToCheck); 
的[?我如何linkify在PHP字符串的URL(
0

使用Daring Fireball上提供的这个正则表达式来匹配一个URL。