Liam Bailey
Liam Bailey

Reputation: 5905

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++ ?

Upvotes: -1

Views: 221

Answers (2)

mickmackusa
mickmackusa

Reputation: 48041

Match the last two digits using preg_replace_callback() (there are many regex patterns which can do this), then use ++ inside the callback to increment the string.

Code: (Demo)

$filename = '2024082009.pdf';
echo preg_replace_callback(
         '/\d{2}\b/',
         fn($m) => ++$m[0],
         $filename
     );
// 2024082010.pdf

Upvotes: 0

gokujou
gokujou

Reputation: 1491

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

Upvotes: 1

Related Questions