我正在尝试使用PHP在字符串中查找JSON字符串。
因此,如果字符串完全是JSON,PHP可以像这样解析它:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
但如果我有一个像
这样的字符串怎么办?$str = 'I have a string that contains JSON like this : {"a":1,"b":2,"c":3,"d":4,"e":5} and then string continues';
如何从中解析JSON?
谢谢!
感谢您的所有答案。他们真的帮助了我。我应该补充一点,在我的情况下,字符串将采用以下形式:
$str = 'some string and some more string [[delimiter]] json={"a":1,"b":2}';
并且,我不是downvoter:)
答案 0 :(得分:2)
你需要一个严肃的正则表达式,例如here,我已经做了很小的改动,以匹配作为子串:
$str = 'I have a string [123,456] that contains JSON like this : {"a":1,"b":2,"c":3,"d":4,"e":5} and then string continues';
$pcre_regex = '
/
(?(DEFINE)
(?<number> -? (?= [1-9]|0(?!\d) ) \d+ (\.\d+)? ([eE] [+-]? \d+)? )
(?<boolean> true | false | null )
(?<string> " ([^"\\\\]* | \\\\ ["\\\\bfnrt\/] | \\\\ u [0-9a-f]{4} )* " )
(?<array> \[ (?: (?&json) (?: , (?&json) )* )? \s* \] )
(?<pair> \s* (?&string) \s* : (?&json) )
(?<object> \{ (?: (?&pair) (?: , (?&pair) )* )? \s* \} )
(?<json> \s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) \s* )
)
(?&json)
/six
';
if (preg_match_all($pcre_regex, $str, $matches)) {
print_r($matches[0]);
}
返回:
Array
(
[0] => [123,456]
[1] => {"a":1,"b":2,"c":3,"d":4,"e":5}
)
<强>更新强>
您可以在表达式中添加锚点以匹配,例如:
json=(?<expr>(?&json))\Z
答案 1 :(得分:1)
您应该在放入字符串的JSON周围创建自己的特殊分隔符。如果你真的不能这样做,你可以尝试在'{“'和'}之间查看,但如果它们在你的字符串中的其他位置它将无法工作。你可以使用这个自定义函数:
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$fullstring = 'I have a string that contains JSON like this : {"a":1,"b":2,"c":3,"d":4,"e":5} and then string continues';
$parsed = get_string_between($fullstring, '{"', '}';
echo $parsed;
答案 2 :(得分:0)
preg_match('/(\{.+\})/', $str, $result);
echo $result[0];
如果字符串的其余部分不包含花括号,则应该这样做。