0

I've been beating my head on this one, and can't figure out a regexp to accomplish the following:

Input string (this is JSON data surrounded by lots of other JSON):

$string=..."natural_order":"12"...

where 12 could also be a decimal like "1.2", or could be larger like 1288 or 1.288.

Desired string:

..."natural_order":12...

Using php preg_replace, so far I've gotten:

preg_replace('/[^natural_order:]+"/', '', $string);

but only returns:

"12"

Any thoughts are greatly appreciated!

1

2 Answers 2

2

Instead of tricky regexen, I'd suggest something along these lines:

$array = json_decode($string, true);
array_walk_recursive($array, function (&$value, $key) {
    if ($key == 'natural_order') {
        $value = strpos($value, '.') ? (float)$value : (int)$value;
    }
});
$string = json_encode($array);
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah, that's the thing I didn't want to write out... ;-)
@Over I think this was faster to write out than trying to mind bend the right regex... ;)
Of note, anonymous functions (AKA closures) require PHP 5.3 or newer. But that can be rewritten using the old-style callbacks.
0

I can think of two solutions. The first, which I won't bother writing out, would be to decode the JSON using json_decode, correct the values by parsing them into ints, and re-encoding the string.

The second is to continue down your path. However, JSON is a fairly complicated string, and can't be reliably parsed using just a regex. If you are confident that the pattern "natural_order":"value" won't show up somewhere else, you could try this:

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

This should match any encapsulated key, followed by a colon, followed by an encapsulated valid floating point number. There's also escapes in case there are spaces around the colon.

1 Comment

I updated my example. I had an extra ` \ ` hiding in the replacement string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.