PHP: Concatenate a leading zero to single digit numbers in string

后端 未结 1 1028
慢半拍i
慢半拍i 2021-01-29 03:11

I have this sample string: hello77boss2america-9-22-fr99ee-9. A leading 0 should be added in front of all the single digit numbers of the string. The result should

相关标签:
1条回答
  • 2021-01-29 03:45

    You can use preg_replace to find the lone digits and replace them, something like...

    <?php
    echo preg_replace(
        '~(?<!\d)(\d)(?!\d)~',
        '0$1',
        'hello77boss2america-9-22-fr99ee-9'
    ); //hello77boss02america-09-22-fr99ee-09
    

    Here's a slightly more descriptive version.

    <?php
    $callback = function($digit) {
    
        $digit = $digit[0];
    
        if (1 == strlen($digit)) {
            $digit = "0$digit";
        }
    
        return $digit;
    };
    
    echo preg_replace_callback('~\d+~', $callback, 'hello77boss2america-9-22-fr99ee-9');
    // hello77boss02america-09-22-fr99ee-09
    
    0 讨论(0)
提交回复
热议问题