【问题标题】:Why does my regex return empty in the capturing subpattern?为什么我的正则表达式在捕获子模式中返回空?
【发布时间】:2018-07-01 04:01:53
【问题描述】:

我已经编写了这些代码来将类似 url 的文本转换为超链接:

$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/www\.[a-zA-Z0-9]{5}\.com(\w*)(\/\S*)?/";
echo preg_replace($reg_exUrl, '<a href="$1://www.$2.com">$1://www.$2.com$3</a>','http://www.abcde.com/index.html');

输出是:

<a href="http://www..com">http://www..com/index.html</a>

但是 $2 是空的 - 这是为什么呢?

【问题讨论】:

  • $2 引用了(\w*),你把它放在.com 之后和/ 之前,这意味着它几乎总是空的。
  • 您可以看到 here 您的第 2 组没有捕获任何内容。
  • 那么如何获取 www 和 .com 之间的字符串?

标签: php regex preg-replace


【解决方案1】:

我想你想要这样的东西:

(http|https|ftp|ftps)\:\/\/www\.([a-zA-Z0-9]{5})\.com(\w*\/\S*)?

https://regex101.com/r/MJ3A6K/1

【讨论】:

  • 我粘贴的链接显示了如何捕获 $2。我不相信 GrumpyCrouton 的回答。
  • @NimsPatel 我检查了 amasmiller 发布的内容。它与 GrumpyCrouton 发布的内容不同。
猜你喜欢
  • 2016-06-04
  • 2014-04-21
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多