Search code examples
phpregexpreg-match

PHP preg_match check filename ends with bracketed number (e.g. filename(1).pdf)


I am looking for a preg_match regex that can detect whether filename (as string, with extension included) has (n) at the end of it. If filename doesn't have (n), it will append (n) at the end of the filename. If filename has (n), it will change to (n + 1) at the end of the filename.


Solution

  • You could use preg_replace_callback to process the filenames, using a regex which checks for an optional (n) before the file extension, and using a callback to return that number incremented if it exists, otherwise 1.

    $filenames = [
        'abc(3).jpg',
        'xyz.pdf'
        ];
        
    foreach ($filenames as $filename) {
        echo preg_replace_callback('/(?:\((\d+)\))?(\.[^.]+$)/', 
            function($matches) { 
                $version = empty($matches[1]) ? 0 : $matches[1];
                return '(' . ($version + 1) . ')' . $matches[2];
            },
            $filename);
        echo "\n";
    }
    

    Output:

    abc(4).jpg
    xyz(1).pdf
    

    Demo on 3v4l.org