【问题标题】:PHP url create from stringPHP url 从字符串创建
【发布时间】:2011-01-24 10:11:57
【问题描述】:

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

我该怎么做?

【问题讨论】:

标签: php regex url


【解决方案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);

【讨论】:

【解决方案2】:

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

【讨论】:

  • 我一定会去看看 :)
  • 这里是完整版(它很长):(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()&lt;&gt;]+|\(([^\s()&lt;&gt;]+|(\([^\s()&lt;&gt;]+\)))*\))+(?:\(([^\s()&lt;&gt;]+|(\([^\s()&lt;&gt;]+\)))*\)|[^\s!()[]{};:'".,?«»“”'']))`跨度>
  • 这里是缩短版(仅匹配 http 地址):(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()&lt;&gt;]+|\(([^\s()&lt;&gt;]+|(\([^\s()&lt;&gt;]+\)))*\))+(?:\(([^\s()&lt;&gt;]+|(\([^\s()&lt;&gt;]+\)))*\)|[^\s!()[]{};:'".,?«»“”'']))`
  • 同样来自上面的 Daring Fireball 页面:Update: A few readers have asked what the licensing terms are for using this pattern in their own code. This pattern is free for anyone to use, no strings attached. Consider it public domain.
猜你喜欢
  • 2012-09-25
  • 2015-05-28
  • 2011-06-17
  • 2014-09-04
  • 2015-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-10
相关资源
最近更新 更多