How can I add this preg_match to my PHP script?

67 views Asked by At

I have a script for finding files with a higher revision (based on a file naming convention).

I.E Ultimate Spreadsheet (Rev A).xls gets removed if Ultimate Spreadsheet (Rev B).xls existed. It does the same with version numbers pretty well. I'm looking to add functionality for basically the same thing to happen - but to include files with no "Rev", as some filenames have no "Rev" at all.

So for example I wanted to add functionality for:

Ultimate Powerpoint.ppt to be removed if Ultimate Powerpoint (Rev A).ppt or Ultimate Powerpoint (Rev B).ppt existed. I think I almost have the code to do this already based on it working with the first rule mentioned above, but I didn't write it myself and am pretty naff with PHP so was wondering if someone could point me in the right direction. Many thanks! My current code:

$fileList = trim(shell_exec("ls -a -1"));
$fileArray = explode("\n", $fileList);

shell_exec('mkdir -p Removed');



// Do this magic for every file
foreach ($fileArray as $thisFile)
{
    if (!$thisFile) continue;
    // Probably already been removed
    if (!file_exists($thisFile)) continue;

    $niceName = trim(preg_replace('%[\(|\[].*%', '', $thisFile));
    preg_quote(pathinfo($thisGame, PATHINFO_EXTENSION), '/') . '$/', '', $thisFile);


// Check for reversions e.g. (Rev 2) or (Rev A)
    if (preg_match('%\(Rev (\d|[A-Za-z])\)%', $thisFile, $revNum))
    {
        if (is_numeric($revNum[1]))
        {
            $revNum = intval($revNum[1]);
        }
        else
        {
            $revNum = ord($revNum[1]);
        }
    }

    $otherVersions = trim(shell_exec("ls -1 \"{$niceName} (\"*\"(Rev \"* 2>/dev/null"));
    if ($otherVersions)
    {
        $otherVersionArray = explode("\n", $otherVersions);
        foreach ($otherVersionArray as $otherFile)
        {
            preg_match('%\(Rev (\d|[A-Za-z])\)%', $otherFile, $thisRev);
            if (is_numeric($thisRev[1]))
            {
                $thisRev = intval($thisRev[1]);
            }
            else
            {
                $thisRev = ord($thisRev[1]);
            }

            if (isset($revNum) && $revNum < $thisRev)
            {
                // Other version is newer, bin ours
                echo "{$thisFile} has an inferior version number/letter [{$revNum} VS. {$thisRev}] - Moved to Removed folder.\n";
                shell_exec("mv ".escapeshellarg($thisFile)." Removed/");
                continue 2;
            }
        }
    }
}
0

There are 0 answers