使用 PHP 正则表达式从 html 中提取 JSON 对象



阅读所有相关线程后,我找不到任何显示正则表达式的内容,该正则表达式能够从 html 内容中提取完整的 json 对象,所以我希望有人可以帮助我获得正确的正则表达式来解决问题。

例如,要提取的 json im 如下所示:

"taxonomy": {"page":"/products/1/","price":"350.00","country_code":"gb","brand":"apple"},

我试图提取 html 中 java 脚本函数内的整个"分类"对象。

我已经尝试过preg_match('/taxonomys*=(.+)(?:;|/', $file, $m);但没有快乐和正则表达式是我试图学习的东西。

我的目标是让正则表达式解析 html 并从 html 中提取分类对象,所以我留下以下内容:{"page":"/products/1/","price":"350.00","country_code":"gb","brand":"apple"}我可以json_decode

如果有人能帮助我获得正确的正则表达式,我将不胜感激,谢谢。

这个正则表达式模式应该可以工作,但这取决于你的完整 HTML 是什么样子的

<?php
$file = '"taxonomy": {"page":"/products/1/","price":"350.00","country_code":"gb","brand":"apple"},
';
preg_match('@"taxonomy":(.*?)},@s', $file, $m);
if(!empty($m[1])){
$jsonString = "[".$m[1] . "}]";
$array = json_decode($jsonString, true);
print_r($array);
}

https://regex101.com/r/fytDO8/1/

最新更新