php爬取网页当中的js对象, json的key值没加引号 php 的 json_decode 无法识别 现在想把 所有的key值加引号正则匹配如何写呢? 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 取回来当string处理吧, $s =<<< JS{a:123, b :"abc"}JS;$s = preg_replace_callback('/(?<=[{,])[^:]+/', function($m) { return '"' . trim($m[0], '\'" ') . '"'; }, $s);print_r(json_decode($s, 1));Array( [a] => 123 [b] => abc) <?php /** 兼容key没有双引括起来的JSON字符串解析 * @param String $str JSON字符串 * @param boolean $mod true:Array,false:Object * @return Array/Object */ function ext_json_decode($str, $mode=false){ if(preg_match('/\w:/', $str)){ $str = preg_replace('/(\w+):/is', '"$1":', $str); } return json_decode($str, $mode); } $str = '{"name":"fdipzone"}'; var_dump(ext_json_decode($str, true)); // array(1) { ["name"]=> string(8) "fdipzone" } $str1 = '{name:"fdipzone"}'; var_dump(ext_json_decode($str1, true)); // array(1) { ["name"]=> string(8) "fdipzone" } ?> 参考:http://blog.csdn.net/fdipzone/article/details/39307223 花瓣网(www.huaban.com)图片地址问题? 如果保存2次session的值? cakephp email 问题 大家帮忙看看,怎么办? 很难的float转换问题 PHP5.2.2的file_exists函数,救命啊 谁给介绍一个PHP做的网站(典型些、中文的)? 为什么升级PHP后,所有错误都没提示了 PHP中chr(13).chr(10)当作一个字符处理,如fread,substr.怎么解决? mysql+php 成绩批量录入 代码放入网页中 用php写个数据库操作的工具
{a:123, b :"abc"}
JS;$s = preg_replace_callback('/(?<=[{,])[^:]+/', function($m) {
return '"' . trim($m[0], '\'" ') . '"';
}, $s);
print_r(json_decode($s, 1));Array
(
[a] => 123
[b] => abc
)
<?php
/** 兼容key没有双引括起来的JSON字符串解析
* @param String $str JSON字符串
* @param boolean $mod true:Array,false:Object
* @return Array/Object
*/
function ext_json_decode($str, $mode=false){
if(preg_match('/\w:/', $str)){
$str = preg_replace('/(\w+):/is', '"$1":', $str);
}
return json_decode($str, $mode);
}
$str = '{"name":"fdipzone"}';
var_dump(ext_json_decode($str, true)); // array(1) { ["name"]=> string(8) "fdipzone" }
$str1 = '{name:"fdipzone"}';
var_dump(ext_json_decode($str1, true)); // array(1) { ["name"]=> string(8) "fdipzone" }
?>
参考:http://blog.csdn.net/fdipzone/article/details/39307223