PHP在json字符串中的数字前后添加双引号 [英] PHP Add double quotes before and after numbers in json string
问题描述
我正在尝试在json字符串中的数字上添加双引号.例如:
I'm trying to add double quotes to numbers in a json string. For example:
{"id":1, "result": 288230376201306378}
应该是:
{"id":1, "result": "288230376201306378"}
我该如何实现?我在某处阅读了我应该使用正则表达式的地方.不幸的是,我对此很陌生.
How do I achieve this? I read somewhere that I'm supposed to use regular expressions. Unfortunately, I'm kinda new to that.
此外,如果您能向我指出一些有助于我了解正则表达式的在线资源,我将不胜感激.
Also, I would be very grateful if you could point me to some online resources which would help me understand regex.
谢谢.
推荐答案
{"id":1,结果":288230376201306378}
{"id":1, "result": 288230376201306378}
id
也是一个数字,如果您也想修改它,请使用:
The id
is also a number, if you want to modify it too, use :
$myJsonString = '{"id":1, "result": 288230376201306378}';
$myNewJsonString = preg_replace('/"([^"]+)":\s*(\d+)/', '"\1": "\2"', $myJsonString);
如果只想修改result
,请使用:
If you only want to modify the result
use :
$myJsonString = '{"id":1, "result": 288230376201306378}';
$myNewJsonString = preg_replace('/"result"\s*:\s*(\d+)/', '"result": "\1"', $myJsonString);
关于正则表达式的问题,互联网上有很多教程.我个人使用 regex101 实时测试我的正则表达式(还有一个快速参考",其中总结了主要标记)在正则表达式中使用.)
For your question about regex, there are many tutorials on internet. I personally use regex101 to test my regex in real time (there is also a "quick reference", which summarize the main tokens used in regex).
由于在这种情况下正则表达式不是最佳解决方案,因此您可以将数字转换为字符串,然后再将其添加到数组(string)$myNumber
中. json_encode
整个数据时,数字将被视为字符串,并且会添加引号.
Since regex are not an optimal solution in this case, you can cast your numbers into string before adding them to your array (string)$myNumber
. The numbers will be considered as strings and quotes will be added when you json_encode
the whole data.
这篇关于PHP在json字符串中的数字前后添加双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!