0

このサンプル文字列があります: hello77boss2america-9-22-fr99ee-9. 文字列のすべての 1 桁の数字の前に先頭の 0 を追加する必要があります。結果は次のようになります。hello77boss02america-09-22-fr99ee-09

以下のコードを試しました:

str_replace("(0-9)","0",$num);
4

1 に答える 1

4

preg_replaceを使用して、孤独な数字を見つけて置き換えることができます...

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

これはもう少し説明的なバージョンです。

<?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
于 2013-08-10T19:59:29.783 に答える