preg_match_all表示字符串某些部分的数字

时间:2018-01-25 21:37:49

标签: php regex preg-match-all

Babylon 5 Season 4 Episode 13 Rumors Bargains and Lies 45

我如何提取赛季后的数字以及仅在赛后没有任何数字的数字。在上面的例子中。我想要预先使用preg_match使用php只需要4和13个数字

3 个答案:

答案 0 :(得分:2)

您可以这样做:

$str = 'Babylon 5 Season 4 Episode 13 Rumors Bargains and Lies 45';

if (preg_match_all("/(Season|Episode) (\d.)/", $str, $matches)) {
    var_dump($matches);
}

它会输出:

   array (size=3)
      0 => 
        array (size=2)
          0 => string 'Season 4 ' (length=9)
          1 => string 'Episode 13' (length=10)
      1 => 
        array (size=2)
          0 => string 'Season' (length=6)
          1 => string 'Episode' (length=7)
      2 => 
        array (size=2)
          0 => string '4 ' (length=2)
          1 => string '13' (length=2)

答案 1 :(得分:1)

您可以将SeasonEpisode值放在数组m中:

preg_match_all('/.*Season\s+(?<season>\d+)\s+Episode\s+(?<episode>\d+)/', $str, $m);

print 'Season: ' . $m['season'][0] . "\n";
print 'Episode: ' . $m['episode'][0] . "\n";

答案 2 :(得分:0)

你可以使用正则表达式来捕捉数字。

(?<=Season)\s*?\d+|(?<=Episode)\s*?\d+

它应该捕获4和13。

请参阅https://regex101.com/r/JVOUOw/2