【问题标题】:php preg_match_all() not working as expectedphp preg_match_all() 没有按预期工作
【发布时间】:2017-05-29 22:23:28
【问题描述】:

在下面的示例字符串中,我有 5 次 #A# 和 11 次 #B# 但 preg_match_all 只返回一个匹配 #A##B# 有 0 个匹配项。知道如何解决这个问题吗?

$string = '<div>#Α#</div><div i="">#Α#</div><div i=""><a href="#Β#" class="" s="" p="65" t="4"></a><a href="#Β#" class="" s="" p="65" t="4"></a><a href="#Β#" class="" s="" p="68" t="4"></a><a href="#Β#" class="" s=""></a><a href="#Β#" class="" s="" p="75" t="2"></a><a href="#Β#" class="" s=""></a><a href="#Β#" class="" s="" p="65" t="3"></a><a href="#Β#" class="" s="" p="60" t="4"></a><a href="#Β#" class="" s=""></a><a href="#Β#" class="" s="" p="60" t="4"></a><a href="#Β#" class="" s="sv_plus" p="75" t="3"></a><noscript><center><h1 style="color:red;font-size:50px">#A#</h1></center><div>#Α#</div></noscript><div>#Α#</div>';

preg_match_all("/\#A\#/",$string,$matches);
print_r($matches); //return only one match instead 5

preg_match_all("/\#B\#/",$string,$matches);
print_r($matches); //return zero matches instead 11

【问题讨论】:

  • 难以置信,我不知道为什么!!!
  • 还不确定问题,但您可以使用这个有用的测试器来玩它:phpliveregex.com/p/kfs
  • 谁是拒绝这个问题的愚蠢人?我真的找不到任何理由。
  • @CasimiretHippolyte:可能有人(正确地)认为用正则表达式解析 HTML 是一个糟糕的主意。不过,这不是对问题投反对票的好理由,尤其是因为这个特定问题甚至与这里有 HTML 的事实无关。
  • @ThiefMaster:你可能是对的。

标签: php regex


【解决方案1】:

这是因为你的字符串只包含一次#A#,不包含#B#

它确实包含了四次 #Α# 和 11 次 #Β#

区别在于第二个版本包含Greek Capital Letter AlphaGreek Capital Letter Beta,而不是ascii A和B。

【讨论】:

  • 你是怎么发现的?
  • @DavidFindlay 我按 F12 并将 #Α# 从他的源粘贴到我的浏览器控制台,然后将其更改为 '#Α#'.split('').map( x =&gt; x.charCodeAt() )。我以前见过类似的问题,所以这是我的第一个预感。
  • @MTK 顺便说一句,用反斜杠转义 # 无效
猜你喜欢
  • 2021-01-16
  • 1970-01-01
  • 2014-03-12
  • 2012-01-16
  • 2011-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多