需要前置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
我试着想出一个正则表达式,失败了。
$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
使用以下模式'/((?<= |^)[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
作为前缀
这是一种非正则表达式的实现方式:
$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);