4

So i will provide this simple example of json string covering most of my actual string cases:

"time":1430702635,\"id\":\"45.33\",\"state\":2,"stamp":14.30702635,

And i'm trying to do a preg replace to the numbers from the string, to enclose them in quotes, except the numbers which index is already quoated, like in my string - '\state\':2 My regex so far is

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

The rezulting string i'm tring to obtain in this case is having the "\state\" value unquoted, skipped by the regex, because it contains the \" ahead of :digit,

"time":"1430702635",\"id\":\"45.33\",\"state\":2,"stamp":"14.30702635",

Why is the '\state\' number replaced also ?

Tried on https://regex101.com/r/xI1zI4/1 also ..

New edit:

So from what I tried,

  (?!\\")

is not working !!

If I'm allowed, I will leave this unanswered in case someone else does know why.

My solution was to use this regex, instead of NOT, I went for yes ..

$string2 = preg_replace('/(\w":)([0-9\.]+)(,)/', '$1"$2"$3',$string);

Thank you.

ion
  • 540
  • 7
  • 20
  • cant you just decode it first then cast all elements to string, then reencode again – Kevin May 04 '15 at 02:29
  • No as I would loose big integers http://stackoverflow.com/questions/8663298/json-transfer-of-bigint-12000000000002539-is-converted-to-12000000000002540 – ion May 04 '15 at 02:31
  • Here's a solution for your current case but I think this could be done much better... `preg_replace('~(("time":)([0-9.]+),|("stamp":)([0-9.]+),)~', '$2$4"$3$5",',$string);` – chris85 May 04 '15 at 03:06
  • @chris85 my string is just an example, my actual string is like 100kb long and can't cover everything with literal words .. I think I should reformulate my problem.. – ion May 04 '15 at 03:17
  • Is there something consistent about all numbers that should have quotes? Greater than 5 decimal places, starts with 143, etc.? – chris85 May 04 '15 at 03:20
  • @chris85 - my example string covers most of the cases, i'm interested why the (?!\\\") is not skipping the \state\" .. – ion May 04 '15 at 03:33

1 Answers1

1

(?!\\") is a negative lookahead, which generally isn't useful at the very beginning of a regular expression. In your particular regex, it has no effect at all: the expression (?!(\\\"))(\:) means "empty string not followed by slash-quote, then a colon" which is equivalent to just trying to match a colon by itself.

I think what you were trying to accomplish is a negative lookbehind, which has a slightly different syntax in PCRE: (?<!\\"). Making this change seems to match what you want: https://regex101.com/r/xI1zI4/2

radiaph
  • 4,001
  • 1
  • 16
  • 19