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 回答
2

这是实现它的非正则表达式方法:

$line = "this 4 is";

$words = explode(' ', $line);
foreach ($words as &$word) {
    if (ctype_digit($word)) {
        $word = str_pad($word, 2, '0', STR_PAD_LEFT);
    }
}

echo implode(' ', $words);
于 2013-04-19T01:51:26.617 回答