Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepend 0 to a single digit if it leads, ends, or exists in the middle of a string separate from another character

Tags:

php

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.

like image 663
kylex Avatar asked Dec 21 '22 06:12

kylex


2 Answers

$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

like image 103
zerkms Avatar answered May 26 '23 16:05

zerkms


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:

  • not followed by a digit itself: (?![0-9])
  • and prepended by a whitespace or the start of the line: ((?<= |^)

will get prefixed with a 0.

like image 45
hek2mgl Avatar answered May 26 '23 16:05

hek2mgl