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 use PHP regex to match an exact string?
- How to use PHP regex with zero or more occurrences?
- How to use PHP regex to match a nbsp HTML whitespace?
- How to use PHP regex to match a zip code?
- How to use PHP regex to get a YouTube video ID?
- How to match a space using PHP regex?
- How to use PHP regex with the "x" modifier?
- How to use PHP regex to match a year?
- How to use PHP regex to match UUID?
- How to use the "s" modifier in PHP regex?
See more codes...