Skip to content
Advertisement

Add leading zero to numeric strings containing decimal value if no leading number

I have about 200 lines in text file

values can be like

$array = ['.1','1.5','0.10','.8'....];

And I am looking specific regex pattern for replace .number like ‘.1’ or ‘.8’

 preg_replace('/.(d+)/','0${0}',$array[0]);

It’s working, but for value 1.5 it’s output is 10.5 and that’s wrong.

Advertisement

Answer

If all of your values are float or integer expressions, then you can use bluntly use “start of string followed by literal dot”: (Demo)

$array = ['.1', '1.5', '0.10', '.8'];
var_export(preg_replace('/^./', '0.', $array));

If you need to make sure that the dot at the start of the string is followed by a digit, you could add a lookahead: (Demo)

var_export(preg_replace('/^.(?=d)/', '0.', $array));

Either way, you don’t need to leverage any capture groups or backreferences.

It may be useful for you to know that preg_replace() will happily iterate your array on its own — no additional loop needs to be written.


If you’d like to directly manipulate your txt file, just add a m pattern modifier so that ^ means the start of each line. (Demo)

$txt = <<<TEXT
.1
1.5
0.10
.8
TEXT;
echo preg_replace('/^.(?=d)/m', '0.', $txt);

Output:

0.1
1.5
0.10
0.8
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement