dongou3158 2013-06-13 17:11
浏览 75
已采纳

PHP:str_pad和反向引用

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);
  • 写回答

1条回答 默认 最新

  • dongtan2017 2013-06-13 17:23
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?