在字符串中查找JSON字符串 [英] Find JSON strings in a string
问题描述
我正在寻找一种在字符串中查找JSON数据的方法.像wordpress简码一样思考它.我认为最好的方法是使用正则表达式.我不想解析JSON,只需查找所有出现的情况即可.
I am looking for a way to find JSON data in a string. Think about it like wordpress shortcodes. I figure the best way to do it would be a regular Expression. I do not want to parse the JSON, just find all occurences.
正则表达式中是否有一种方法可以使括号的数量匹配?目前,当我嵌套对象时遇到了这个问题.
Is there a way in regex to have matching numbers of parentheses? Currently I run into that problem when having nested objects.
简单的演示示例:
This is a funny text about stuff,
look at this product {"action":"product","options":{...}}.
More Text is to come and another JSON string
{"action":"review","options":{...}}
因此,我想拥有两个JSON字符串. 谢谢!
As a result i would like to have the two JSON strings. Thanks!
推荐答案
从给定文本中提取JSON字符串
由于您正在寻找一种简单的解决方案,因此可以使用以下使用递归的正则表达式来解决匹配括号集的问题.它递归地匹配{
和}
之间的所有内容.
Extracting the JSON string from given text
Since you're looking for a simplistic solution, you can use the following regular expression that makes use of recursion to solve the problem of matching set of parentheses. It matches everything between {
and }
recursively.
尽管,您应该注意,不能保证此方法在所有可能的情况下都适用.它仅用作快速JSON字符串提取方法.
Although, you should note that this isn't guaranteed to work with all possible cases. It only serves as a quick JSON-string extraction method.
$pattern = '
/
\{ # { character
(?: # non-capturing group
[^{}] # anything that is not a { or }
| # OR
(?R) # recurses the entire pattern
)* # previous group zero or more times
\} # } character
/x
';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);
输出:
Array
(
[0] => {"action":"product","options":{...}}
[1] => {"action":"review","options":{...}}
)
在PHP中,了解JSON字符串是否有效的唯一方法是应用json_decode()
.如果解析器理解JSON字符串并且符合定义的标准,则json_decode()
将创建JSON字符串的对象/数组表示形式.
In PHP, the only way to know if a JSON-string is valid is by applying json_decode()
. If the parser understands the JSON-string and is according to the defined standards, json_decode()
will create an object / array representation of the JSON-string.
如果您想过滤掉无效的JSON,则可以使用 array_filter()
具有回调功能:
If you'd like to filter out those that aren't valid JSON, then you can use array_filter()
with a callback function:
function isValidJSON($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
$valid_jsons_arr = array_filter($matches[0], 'isValidJSON');
这篇关于在字符串中查找JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!