php preg_match and 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 的 return 值为 0。

我的代码:

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

请注意,在双引号字符串中,您需要使用双反斜杠来转义正则表达式 shorthand 类.

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

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

参见IDEONE demo。结果:The Big Bang Theory.

反向引用</code>将恢复剧集子串前后的子串。</p> <p>因为你使用了<code>/i修饰符,所以你不需要使用[eE][Ss],任何情况下只需使用单个字母即可。

对于 return 剧集之前的子字符串和剧集子字符串本身,只需使用带有 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

another demo

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

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

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