PHP正则应用12 —— 贪婪和非贪婪

本文介绍了PHP中正则表达式的贪婪与非贪婪模式的区别及应用。通过具体实例,展示了如何使用这两种模式来精确匹配字符串中的目标内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

贪婪模式

$str = 'ksda good  gooooood good kl s ja dafdg fgsege'; 

$patt = '/g.+d/';

preg_match_all($patt,$str,$res);

var_dump($res);
/*
array (size=1)
  0 => 
    array (size=1)
      0 => string 'good  gooooood good kl s ja dafd' (length=32)
*/

.点匹配任意字符
g开头d结尾中间任意字符的所有


非贪婪模式

$str = 'ksda good  gooooood good kl s ja dafdg fgsege'; 

$patt = '/g.+?d/';

preg_match_all($patt,$str,$res);

var_dump($res);
/*
array (size=1)
  0 => 
    array (size=3)
      0 => string 'good' (length=4)
      1 => string 'gooooood' (length=8)
      2 => string 'good' (length=4)
*/

加?
即可匹配到有g开头d结尾的单词