4

先頭に 0 を付ける必要がある「文」の例:

5 this is 3になる05 this is 03

44 this is 2となる44 this is 02(注44は一桁ではないので先頭に付かない)

this 4 isになるthis 04 is


先頭に 0 を付けない「文」の例:

44 this is

22 this3 is(注 3 は文字列の一部として存在するため、先頭に追加されません)

this is5

私は正規表現を考え出そうとしましたが、惨めに失敗しました。

4

3 に答える 3

6
$str = '5 this is 3';

$replaced = preg_replace('~(?<=\s|^)\d(?=\D|$)~', '0\\0', $str); // 05 this is 03

正規表現は次のことを意味します:\dスペースまたは文字列の先頭が前に(?<=\s|^)あり、数字以外または文字列の末尾が後に続くすべての数字 ( ) (?=\D|$)- 先頭に0

ライブデモ: http://ideone.com/3B7W0n

于 2013-04-19T01:45:27.680 に答える
3

で次のパターンを使用し'/((?<= |^)[0-9](?![0-9]))/'ますpreg_replace()

私は小さなテストスクリプトを書きました:

$pattern = '/((?<= |^)[0-9](?![0-9]))/';
$replacement = "0$1";

$tests = array(
    '5 this is 3' => '05 this is 03',
    '44 this is 2' => '44 this is 02',
    'this 4 is' => 'this 04 is',
    '44 this is' => '44 this is',
    'this is5' => 'this is5'
);

foreach($tests as $orginal => $expected) {
    $result = preg_replace($pattern, $replacement, $orginal);
    if($result !== $expected) {
        $msg  = 'Test Failed: "' . $orginal . '"' . PHP_EOL;
        $msg .= 'Expected: "' . $expected . '"' . PHP_EOL;
        $msg .= 'Got     : "' . $result . '"'. PHP_EOL;
        echo 'error' . $msg;
    } else {
        $original . '=>' . $result . PHP_EOL;
    }      
}

説明:

アサーションを使用して、次の数字のみを確認[0-9]します。

  • 数字自体が続かない:(?![0-9])
  • 先頭に空白または行頭を追加します。((?<= |^)

の接頭辞が付きます0

于 2013-04-19T01:44:20.283 に答える