phpstringnumbers

String number into number in PHP


Say I have a string like John01Lima

is there any way to pull out the two numbers and have them as numbers that can be incremented with $number++ ?


Solution

  • If your format will always be 'YYYYMMDD00.pdf' I would do this little function:

    function increment_filename($incoming_string)
    {
        // The RegEx to Match
        $pattern = "/[0-9]{2}(?=\.pdf$)/i";
        // Find where it matches
        preg_match($pattern, $incoming_string, $matches);
        // Replace and return the match incremented
        return preg_replace($pattern, $matches[0] + 1, $incoming_string);
    }
    

    If you need it to match any file extension, this should work:

    function increment_filename($incoming_string)
    {
        // The RegEx to Match
        $pattern = "/[0-9]{2}(?=\.[a-z]+$)/i";
        // Find where it matches
        preg_match($pattern, $incoming_string, $matches);
        // Replace and return the match incremented
        return preg_replace($pattern, $matches[0] + 1, $incoming_string);
    }
    

    Hope that helps, was awesome practice to hone my RegEx skills. :)