PHP 困难 preg_match

PHP difficult preg_match

我正在尝试管理我用于 XBMC 的个人 Web 服务器上的一些文件,但所有文件(来自 YIFY 的电影)的名称都类似于

Jumanji.1995-720p.YIFY.mp4
Silver.Linings.Playbook.2012.1080p.x264.YIFY.mp4
American Hustle (2013) 1080p BrRip x264 - YIFY.mp4

请注意,有些项目用 . 分隔,其他项目用 _ 或空格分隔。

所以我需要做的是 preg_match 文件到一个数组 (title,year,quality) 我只知道一些 preg_match 基础知识。 但这对我来说太难了。

例如

echo extract('American Hustle (2013) 1080p BrRip x264 - YIFY.mp4');

这应该输出=

array(
    'title' => 'American Hustle',
    'year' => '2013',
    'quality' => 1080p
);

提前致谢

^(.*?)\W+(\d{4})(?=[\W ]+?(\d{3,4})p)

您可以尝试 this.See 演示。

https://regex101.com/r/nS2lT4/29

正则表达式开始并捕获从 startnon word letter 的任何内容,它可以是一个或多个并且在 it.After 之前有 4 digits 这个前瞻确保在捕获 \d{4} 之后,有 non word letters 可以是一个或多个,并且在前瞻 it.Because 之前有 4 digitsp 我们捕获最后一个 4 只有非单词字符和 4 digits p 后的数字。

你有 3 种不同的格式,那么你需要 3 种不同的解析类型

试试这个:

$tests = array(
    // format 1
    "Jumanji.1995-720p.YIFY.mp4",
    "Silver.Linings.Playbook.2012-1080p.YIFY.mp4",
    "American.Hustle.2013-1080p.YIFY.mp4",
    // format 2
    "Jumanji.1995.720p.x264.YIFY.mp4",
    "Silver.Linings.Playbook.2012.1080p.x264.YIFY.mp4",
    "American.Hustle.2013.1080p.x264.YIFY.mp4",
    // format 3
    "Jumanji (1995) 720p BrRip x264 - YIFY.mp4",
    "Silver Linings Playbook (2012) 1080p BrRip x264 - YIFY.mp4",
    "American Hustle (2013) 1080p BrRip x264 - YIFY.mp4",
);


function extractInfos($s) {

    $infos = array();

    if (FALSE === strpos($s, ".YIFY.")) {
        // format 3

        $tab = explode(" ", $s);

        $yearIndex = count($tab) - 6;

        $infos["year"] = trim($tab[$yearIndex], "()");
        $infos["quality"] = $tab[$yearIndex + 1];

        array_splice($tab, $yearIndex);
        $infos["title"] = implode(" ", $tab);
    } else {
        // format 1 or 2

        $tab = explode(".", $s);

        $yearIndex = count($tab) - 3;

        if (FALSE === strpos($tab[$yearIndex], "-")) {
            // format 2

            $yearIndex -= 2;

            $infos["year"] = $tab[$yearIndex];
            $infos["quality"] = $tab[$yearIndex + 1];
        } else {
            // format 1
            list($infos["year"], $infos["quality"]) = explode("-", $tab[$yearIndex]);
        }

        array_splice($tab, $yearIndex);
        $infos["title"] = implode(" ", $tab);
    }


    return $infos;
}


echo "<table border=\"1\">";

foreach ($tests as $s) {
    $infos = extractInfos($s);

    ?>
        <tr>
            <td>
                <?php echo $infos["title"];?>
            </td>
            <td>
                <?php echo $infos["year"];?>
            </td>
            <td>
                <?php echo $infos["quality"];?>
            </td>
        </tr>
    <?php
}

echo "</table>";