Eric Eric - 6 months ago 27
PHP Question

Regex replace numbers but the ones starting with 0 that aren't float

Consider the following string:

' "z":"100", "a":"+0.5", "b":"-0.578", "c":"-.5", "d":".55", "e":"-5",
"f":"01234", "g":"0.999", "i":"153.35" '

I'm trying to convert every number in this string while retaining the negative sign, except the ones starting with a 0 that arent float. In other words, I'm trying to convert to

' "z":100, "a":0.5, "b":-0.578, "c":-.5, "d":.55, "e":-5, "f":"01234", "g":0.999, "i":153.35 '

This is what I have so far

preg_replace('/((?:\:")(?:[\+])?[\-]?([0-9\.]+?)[0-9]+(?:"))/', '$1', $string);

Which isn't enough.. The hard part is to keep the " around 01234 while removing them for the other numbers..

Basically I'd like to ignore


Regexr link


You can use the regex "(?!0\d+")\+?(-?(?:\d*\.)?\d+)" and replace it with $1.

See ideone

$str = '"z":"100", "a":"+0.5", "b":"-0.578", "c":"-.5", "d":".55", "e":"-5", "f":"01234", "g":"0.999", "i":"153.35"';
$pattern = '/"(?!0\d+")\+?(-?(?:\d*\.)?\d+)"/';
print(preg_replace($pattern, '$1', $str));