【问题标题】:PHP regular expression find the modify the current matches [duplicate]PHP正则表达式查找修改当前匹配项[重复]
【发布时间】:2013-11-22 20:20:27
【问题描述】:

我有一个字符串,我需要将任何 url 替换为 <a> html 标记

$str='Lorem Ipsum is simply dummy text of http://www.lipsum.com/ the printing';

$outputString=
'Lorem Ipsum is simply dummy text of <a href="http://www.lipsum.com">http://www.lipsum.com/</a> the printing';

【问题讨论】:

标签: php html regex


【解决方案1】:
$str='Lorem Ipsum is simply dummy text of http://www.lipsum.com/ the printing';
$pattern='/\b((https?:\/\/|www.)[\w.\/-?=&#]+)(?=\s)/i';
$replace='<a href="$1">$1</a>';
echo preg_replace($pattern, $replace, $str);

输出:

Lorem Ipsum is simply dummy text of <a href="http://www.lipsum.com/">http://www.lipsum.com/</a> the printing'

Working on RegExr

【讨论】:

  • $1 表示匹配中的第一个捕获组,在本例中为 URL。
  • 模式与此链接youtube.com/watch?v=J4TAWrT4upY和其他链接不匹配
  • 您需要匹配的任何字符只需添加到中间的[...]。我现在将添加?=#&amp;
猜你喜欢
  • 1970-01-01
  • 2015-12-26
  • 1970-01-01
  • 2017-10-11
  • 2013-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多