使用 php preg_replace 解析 JSON 字符串中的目标双引号
我一直在为这个问题绞尽脑汁,无法找出一个正则表达式来完成以下任务:
输入字符串(这是由许多其他 JSON 包围的 JSON 数据):
$string=..."natural_order":"12"...
其中 12 也可以是像“1.2”这样的小数,或者可以更大,如 1288 或 1.288。
所需的字符串:
..."natural_order":12...
使用 php preg_replace,到目前为止我已经得到:
preg_replace('/[^natural_order:]+"/', '', $string);
但仅返回:
"12"
非常感谢任何想法!
I've been beating my head on this one, and can't figure out a regexp to accomplish the following:
Input string (this is JSON data surrounded by lots of other JSON):
$string=..."natural_order":"12"...
where 12 could also be a decimal like "1.2", or could be larger like 1288 or 1.288.
Desired string:
..."natural_order":12...
Using php preg_replace, so far I've gotten:
preg_replace('/[^natural_order:]+"/', '', $string);
but only returns:
"12"
Any thoughts are greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议不要使用棘手的正则表达式,而是按照以下方式进行操作:
Instead of tricky regexen, I'd suggest something along these lines:
我可以想到两种解决方案。第一个(我不想写出来)是使用 json_decode 解码 JSON,通过将值解析为整数来更正值,然后重新编码字符串。
第二是继续走你的路。然而,JSON 是一个相当复杂的字符串,仅使用正则表达式无法可靠地解析。如果您确信模式
"natural_order":"value"
不会出现在其他地方,您可以尝试以下操作:这应该匹配任何封装的键,后跟冒号,后跟封装的键有效的浮点数。如果结肠周围有空间,也有逃逸的方法。
I can think of two solutions. The first, which I won't bother writing out, would be to decode the JSON using
json_decode
, correct the values by parsing them into ints, and re-encoding the string.The second is to continue down your path. However, JSON is a fairly complicated string, and can't be reliably parsed using just a regex. If you are confident that the pattern
"natural_order":"value"
won't show up somewhere else, you could try this:This should match any encapsulated key, followed by a colon, followed by an encapsulated valid floating point number. There's also escapes in case there are spaces around the colon.