Search code examples
phpregexpreg-replacebackreference

PHP: str_pad and backreference


How do I use str_pad with a backreference? The way I'm using it, it reads the characters between the single quotes as characters rather than the backreferenced string. Escaping the single quotes returns an error.

$y = 'CHG1234567';  
$y = preg_replace ('~(((?:CHG|HD|TSK))([1-9][0-9]++))~', '${2}'.(str_pad('$3',10, 0, STR_PAD_LEFT)), $y);
echo $y;
# returns - CHG000000001234567 - 15 digits
# i want - CHG0001234567 - 10 digits

Solution:

$y = preg_replace_callback ('~((?:CHG|HD|TSK))([1-9][0-9]++)~', function($m) { return $m[1] . str_pad($m[2], 10, '0', STR_PAD_LEFT);
}, $y);

Solution

  • Use preg_replace_callback instead of preg_replace:

    $y = preg_replace_callback('~(CHG|HD|TSK)([1-9][0-9]++)~', function ($m) {
        return $m[1] . str_pad($m[2], 10, '0', STR_PAD_LEFT);
    }, $y);