php-preg_match和regex正则表达式


php preg_match and regex regular expression

我想使用正则表达式:

/(.*)[.'s][sS]('d{1,20})[eE]('d{1,100}).*/i

筛选电视连续剧的标题。(例如,《生活大爆炸》S04E05)为了删除情节串(S04E05。

我已经用测试了我的正则表达式http://www.phpliveregex.com/一切都很好。但把它包括在我的网站上,我会得到包括剧集串在内的整个标题。preg_match的返回值为0。

我的代码:

$ret=preg_match("/(.*)[.'s][sS]('d{1,20})[eE]('d{1,100}).*/i", $title,$output);
if($ret==1){
    $title_without=$output[1];
}

请注意,在双引号字符串中,需要使用双反斜杠来转义regex简写类。

您可以在单引号内的preg_replace函数中使用正则表达式,这样就不必使用双反斜杠:

$title= "The Big Bang Theory S04E05";
$ret=preg_replace('/^(.*)[.'s]s'd{1,20}e'd{1,100}(.*)/i', ''1'2', $title);
echo $ret;

请参阅IDEONE演示。结果:The Big Bang Theory

反向引用'1'2将恢复剧集子串之前和之后的子串。

由于您使用的是/i修饰符,所以不需要使用[eE][Ss],在任何情况下都只需使用单个字母。

要返回剧集之前的子字符串和剧集子字符串本身,只需使用带有preg_match的捕获组,如下所示:

$title= "The Big Bang Theory S04E05";
$ret=preg_match('/^(.*)[.'s](s'd{1,20}e'd{1,100})/i', $title, $match);
echo $match[1] . PHP_EOL; // => The Big Bang Theory
echo $match[2];           // => S04E05

请参阅另一个演示

您可以查找单词并匹配除最后一个之外的所有单词:

$matches = array();
$regex = "/^(['w ]*) ['w]+$/i";
$title = "The Big Bang Theory S04E05";
preg_match_all ($regex, $title, $matches);

现在你所有的比赛都在$matches