【问题标题】:PHP regular expression with preg_match_all - why doesn't it match?带有 preg_match_all 的 PHP 正则表达式 - 为什么不匹配?
【发布时间】:2012-11-11 23:36:46
【问题描述】:

我正在寻找一个正则表达式来匹配任何字符。我知道'。是一个占位符,除了换行符。鉴于以下代码:

$fruits = "One\nTwo\nThree";
preg_match_all('/^(.*)$/', $str, $matches);
print_r($matches);

为什么它根本不匹配任何东西?我想,$matches[0] 会是一二三?

【问题讨论】:

标签: php regex-greedy


【解决方案1】:

添加modifier "s" to the regex

如果设置了此修饰符,则模式中的点元字符匹配 所有字符,包括换行符。没有它,换行符被排除在外。 这个修饰符等价于 Perl 的 /s 修饰符。负类 例如 [^a] 总是匹配换行符,独立于 这个修饰符的设置。

$fruits = "One\nTwo\nThree";
preg_match_all('/^(.*)$/s', $fruits, $matches);
print_r($matches);

更新:

如果您将 $fruits 括在单引号中,则换行符不会被视为这样,并且替换也有效,没有“s”修饰符的事件。但我不知道输出是否是你所期望的;)

   $fruits = 'One\nTwo\nThree';
   preg_match_all('/^(.*)$/', $fruits, $matches);
   print_r($matches);

【讨论】:

  • 另外,如果您的正则表达式引擎不支持s 修饰符或类似的,或者您只希望它在一个区域中的行为,您可以使用[\s\S]
猜你喜欢
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多