regex - PHP Regular Expression to extract JSON data -
i have next string:
window['test'] = false; window['options'] = true; window['data'] = { "id" : 2345, "stuff": [{"id":704,"name":"test"};`
how go extracting json info in window['data']
? illustration info provided little sample of exists. there could more info before and/or after window['data']
.
i've tried had no luck:
preg_match( '#window["test"] = (.*?);\s*$#m', $html, $matches );
there several issues can see.
your string uses single quotes: window['test']
not window["test"]
, have in regular expression. means should utilize double quotes enclose regular look (or escape quotes).
your regular look has unescaped brackets, used create character class. should utilize \[
instead of [
.
you looking data
regular look looks test
.
you have $
@ end of regular expression, means won't match if there nil other whitespace after bit matched.
also info seems incomplete, there missing brackets @ end, think copy-paste error.
so try:
php > preg_match("#window\['data'\]\s*=\s*(.*?);#", $html, $matches); php > print_r($matches); array ( [0] => window['data'] = {"id":2345,"stuff":[{"id":704,"name":"test"}; [1] => {"id":2345,"stuff":[{"id":704,"name":"test"} )
of course of study must utilize json_decode()
convert json string ($matches[1]
) object or associative array can use.
php regex
No comments:
Post a Comment