Angelo Angelo - 1 month ago 7
PHP Question

PHP regex for finding token in ugly string

Suppose I have this ugly string:

$uglyString = 'thing.header.setLoadBaseData(true);</script><script type=\'text/javascript\'>window.preload={"serverVersion":"20161019","locale":"en_US","token":{"value":"aAdcDqpeWcaJzmmWeH9ElQ:1477340771943","valid":43200000},"accounts":[{"id":"55153549","datasetId":"a55153549w0p0","s4id":"FU\/llMk3qzAP6ClSIHqMU73huAo=","name":"Ga abd Gub","isPremium":false,"starred":false,"totalNumberOfProfiles":1,"wprops":[{"id":"88276407","datasetId":"a55153549w88276407p0","s4id":"T1xfVTHwcwLUwkUSlzEfZrRYL3E=","name":"GrubHub Preview","number":1,"configuredForAppData":false,"configuredForWebData":true,"isPr';


From the above string, I need to extract the value
aAdcDqpeWcaJzmmWeH9ElQ:1477340771943
using PHP.

It is found next to
token
. The token will always appear like
"token":{"value":"aAdcDqpeWcaJzmmWeH9ElQ:1477340771943"


This is what I have but it is not working

preg_match('/(?<=token":{"value":)(.*)(?=.*)/', $uglyString, $matches);

Answer

Use what is constant and capture what will change:

preg_match('/"token":{"value":"([^"]+)"/', $uglyString, $matches);
echo $matches[1];

So match all of the constant stuff up until the ", then capture everything that is not a " up until the final ".