views:

49

answers:

1

Hi Guys, 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++ ?

+1  A: 

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. :)

gokujou
+1 - very good, very mighty.
mattbasta
Actually it should probably have a conditional statement on the preg_match too now that I think about it. Incase the string happens not to match so we get no errors from trying to access the match array.
gokujou