php-regexHow to use PHP regex to match a JSON key value?
Using PHP regex to match a JSON key value is a powerful way to parse and extract data from a JSON string. The following example code block shows how to use regex to match a JSON key value:
$json = '{"name":"John","age":30,"city":"New York"}';
preg_match('/\"name\":\"(.*?)\"/', $json, $name);
echo $name[1];
The output of the example code is:
John
Code explanation
-
$json = '{"name":"John","age":30,"city":"New York"}';- This is the JSON string that we are trying to parse. -
preg_match('/\"name\":\"(.*?)\"/', $json, $name);- This is the regex expression used to match the JSON key value. The\"name\":\"part of the expression matches the key, and the(.*?)part of the expression matches the value. -
echo $name[1];- This line of code prints out the value of the matched key.
Helpful links
More of Php Regex
- How to match a single quote in PHP regex?
- How to use PHP regex to match a zip code?
- How to use PHP regex to match an XML tag?
- How to use PHP regex to match whitespace?
- How to use PHP regex to match UUID?
- How to use PHP regex to match URL?
- How to use PHP regex to match time?
- How to use PHP regex to get a YouTube video ID?
- How to use PHP regex to match a year?
- How to use PHP regex with the "x" modifier?
See more codes...