dqcz57269 2012-11-11 23:36
浏览 65
已采纳

PHP正则表达式与preg_match_all - 为什么不匹配?

I'm looking at a regular expression to match any characters. I know that the '.' is a placeholder except for newline. Given this code below:

$fruits = "One
Two
Three";
preg_match_all('/^(.*)$/', $str, $matches);
print_r($matches);

Why does it not match anything at all? I would think, $matches[0] would be One Two Three?

  • 写回答

1条回答 默认 最新

  • drpp5680 2012-11-11 23:40
    关注

    Add the modifier "s" to the regex:

    If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier.

    $fruits = "One
    Two
    Three";
    preg_match_all('/^(.*)$/s', $fruits, $matches);
    print_r($matches);
    

    Update:

    If you enclose $fruits in single quotes, the newline isn't treated as such and the replacement also works, event without the "s" modifier. But I don't know if the output is what you expect it to be ;)

       $fruits = 'One
    Two
    Three';
       preg_match_all('/^(.*)$/', $fruits, $matches);
       print_r($matches);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)