2024-10-11

巧妙运用 PHP 正则表达式,解析 JSON 数据的艺术

使用 php 正则表达式解析 json 数据:提取姓名:使用模式 ‘/”name”: “(.+?)”/’。提取年龄:使用模式 ‘/”age”: (.+?)(?=/,)|/z/’。提取地址:使用模式 ‘/”address”: “(.+?)”/’。

巧妙运用 PHP 正则表达式,解析 JSON 数据的艺术

巧妙运用 PHP 正则表达式,解析 JSON 数据的艺术

简介

正则表达式是一种强大的工具,可用于查找、替换或验证文本。在 PHP 中,正则表达式可以用来有效解析 JSON 数据,提取所需的信息。

立即学习PHP免费学习笔记(深入)”;

实战案例

为了演示如何使用 PHP 正则表达式解析 JSON 数据,我们创建一个示例。假设我们有一个 JSON 文件名为 data.json,内容如下:

{
  "name": "John Doe",
  "age": 30,
  "address": "123 Main Street"
}
登录后复制

提取姓名

要使用正则表达式提取名称,我们可以使用以下模式:

preg_match('/"name": "(.+?)"/', $jsonStr, $matches);
登录后复制

这个模式匹配一个双引号包围的名称,其中 .+? 表示非贪婪匹配任何字符序列,直到下一个双引号。

提取年龄

要提取年龄,我们可以使用以下模式:

preg_match('/"age": (.+?)(?=/,)|/Z/', $jsonStr, $matches);
登录后复制

这个模式匹配一个数字(.+?),后面可能有一个逗号或字符串结束((?=/,)|/Z)。

提取地址

要提取地址,我们可以使用以下模式:

preg_match('/"address": "(.+?)"/', $jsonStr, $matches);
登录后复制

这个模式与名称模式类似,它匹配一个双引号包围的地址。

完整代码

$jsonStr = file_get_contents('data.json');

preg_match('/"name": "(.+?)"/', $jsonStr, $matches);
$name = $matches[1];

preg_match('/"age": (.+?)(?=/,)|/Z/', $jsonStr, $matches);
$age = $matches[1];

preg_match('/"address": "(.+?)"/', $jsonStr, $matches);
$address = $matches[1];

echo "Name: $name
"; echo "Age: $age
"; echo "Address: $address
";
登录后复制

输出:

Name: John Doe
Age: 30
Address: 123 Main Street
登录后复制

结论

通过使用 PHP 正则表达式,我们可以轻松提取 JSON 数据中的所需信息,使之易于处理和显示。

以上就是巧妙运用 PHP 正则表达式,解析 JSON 数据的艺术的详细内容,更多请关注php中文网其它相关文章!

https://www.php.cn/faq/1043262.html

发表回复

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