Examples of "sentences" that would require a prepend of 0:
5 this is 3
becomes 05 this is 03
44 this is 2
becomes 44 this is 02
(note 44 is not prepended because it is not a single digit)
this 4 is
becomes this 04 is
Examples of "sentences" that would not get a prepend of 0:
44 this is
22 this3 is
(note 3 is not prepended because it exists as part of a string)
this is5
I tried coming up with a regex and failed miserably.
$str = '5 this is 3';
$replaced = preg_replace('~(?<=\s|^)\d(?=\D|$)~', '0\\0', $str); // 05 this is 03
The regular expression means: every digit (\d
) that is preceded by a space or a beginning of a string (?<=\s|^)
and followed by not digit or the end of a string (?=\D|$)
- replace with itself prepended by 0
Live demo: http://ideone.com/3B7W0n
Use the following pattern '/((?<= |^)[0-9](?![0-9]))/'
with preg_replace()
:
I wrote a little test script:
$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;
}
}
Explanation:
I use assertions to make sure only digits [0-9]
that are:
(?![0-9])
((?<= |^)
will get prefixed with a 0
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With