in Php Basics

Increment Numeric Part Of String

Have you ever needed to increment the number which is part of a string. For example if you have an invoice number with the format und001 and want to be able to automatically create the next invoice number of und002 you need to be able to increment the number. PHP has a built-in way of incrementing either a number or a string simply by placing ++ at the end of the variable.

// Number
$i = 1;


// echo 2
echo $i;

But you can also do this for letters, PHP will increment the variable to the next letter in the alphabet.

// Letter
$a = 'a';


// echo b
echo $a;

Therefore if we have an invoice number of und001 then to get the next number all we have to do is use the ++ syntax to get the next number.

// Invoice
$i = 'und001';


// echo und002
echo $i;

The problem comes if you have a different format such as 001und or invoice-001-und where the invoice number isn't at the end of the string. You need to then search the string for the number of the invoice and set the increment by one. This is where preg_replace_callback function comes in handy, by searching for digits and replacing the number with a plus one.

function increment($matches)
        $length = strlen($matches[1]);
        return sprintf("%0".$length."d", ++$matches[1]);

$invoice = 'invoice001und';

$invoice =  preg_replace_callback( "|(\d+)|", "increment", $invoice);

echo '<p>'.$invoice.'</p>';

This takes the string, searches for digits inside the string and passes these digit values into the function increment in here we return the digit matched plus 1 and return the new number. Now we can increment a number anywhere inside a string.