php – preg_replace with iterator-ThrowExceptions

Exception or error:

I have strings which contain numbers. I need to replace those numbers with other numbers.

The string is complex json and looks something like this (this sample is parts of json joined together as example).


{"attrs":
    {
        "text":"5","fontSize":14,"originX":"center","originY":"center","fill":"#231fff","x":-5,"y":-5
    },
    "className":"Text"
},
{"attrs":
    {
        "text":"9","fontSize":14,"originX":"center","originY":"center","fill":"#231fff","x":-5,"y":-5
    },
    "className":"Text"
}

so I want to replace 5 and 9 with 1 and 2 respectively.

Is there a way to do it with preg_replace or do I have to loop over json and replace numbers there ?

This code will replace all numbers with $i at that moment:

preg_replace('~"attrs":{"text":"(\d+)"~i', '"attrs":{"text":"'.$i.'"', $jsonString); 
$i++;
How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *