获取包含电影标题字符串中的年份的子序列


Get Substr including year in a Movie Title String

我有电影标题

The Abandoned 2015 480p Reformed
The Lady in the Car with Glasses and a Gun 2015 BluRay 720p
Rise of the Footsoldier Part II (2015) 720p

我想要的只是电影标题和年份,例如第一个标题中的例子只是The Abandoned 2015.我有一个正则表达式,可以在标题示例中查找年份,当我在标题中使用strpos(movietitle,year)返回年份的位置时,它会在上述所有标题中返回 2015,但当我使用substr(movietitle,0,-(yearpos))时,它不会给我一个标题和年份,不包括任何内容。

任何有办法做到这一点的人。有许多标题具有不同的字符串长度。

这是我的脚本试图为其中一个获得标题和年份,但未能给我我需要的东西。

$str = "Suffragette 2015 DVDSCR Webz";
if (preg_match('/(^|'s)('d{4})('s|$)/', $str, $matches)) {
    $year = $matches[0];
}else{
    $year = "";
}
if($year != ""){
   $pos = strpos($str,$year);
   echo substr($str,0,-($pos)); //Fail...
}

想出了这个解决方案。

$movt = "Paranormal Activity The Ghost Dimension 2015 720p BluRay x265 HEVC RMTeam";
$arrz = array("(",")");
$str = str_replace($arrz,'',$movt);
if (preg_match('/(^|'s)('d{4})('s|$)/', $str, $matches)) {
    $year = $matches[0];
}else{
    $year = "";
}
if($year != ""){
$pos = strpos($str,$year);
$ext = strlen(substr($str,($pos+5)));
echo substr($str,0,strlen($str)-$ext);
}

Paranormal Activity The Ghost Dimension 2015

试试这个:

$str = "Suffragette 2015 DVDSCR Webz";
if (preg_match('/(^|'s)('d{4})('s|$)/', $str, $matches)) {
    $year = $matches[0];
}else{
    $year = "";
}
if($year != ""){
    $pos = strpos($str,$year);
    // Add 5 to $pos because " 2015" have 5 characters
    echo substr($str,0, (5 + $pos));
}

这适用于您的示例...结果将是 Suffragette 2015 ,但如果您的标题上有任何年份,则脚本的结果将是不完整的标题。


问候。

我用你最上面的三件事对此进行了测试,似乎对它们有用(当然它只有 3 个测试用例)

<?php
$titles = array(
    "The Abandoned 2015 480p Reformed",
    "The Lady in the Car with Glasses and a Gun 2015 BluRay 720p",
    "Rise of the Footsoldier Part II (2015) 720p"
);
//List of titles to look through.
$reg = '/(['w's]+)'(?([0-9]{4})')?/';
foreach($titles as $title){
    if(preg_match($reg,$title,$matches)){
        //If we get a match, keep going
        echo $matches[1]. ' ' . $matches[2].'<br />';
    }
}
?>