duangu1878 2015-08-17 18:23
浏览 21
已采纳

使用preg_replace向数组添加引号

I have this array:

$array = '[[Smarties, 50g, 3, 1.99], 
          [M&Ms Peanut, 49g, 3, 1.99], 
          [Oreo Cookies, 300g, 1, 3.99], 
          [Pepsi, 355ml, 3, 1.29]]';

I need to use json_decode, so I need to find a way to surround the information inside in quotes like this:

[["Smarties", "50g", "3", "1.99"], 
["M&Ms Peanut", "49g", "3", "1"."99"], 
["Oreo Cookies", "300g", "1", "3.99"], 
["Pepsi", "355ml", "3", "1.29"]]

I tried using preg_replace, and this is what I'm currently getting (close, but it's separating the prices into two and also separating two-word names into two.):

[["Smarties", "50g", "3", "1"."99"], 
["M"&"Ms" "Peanut", "49g", "3", "1"."99"], 
["Oreo" "Cookies", "300g", "1", "3"."99"], 
["Pepsi", "355ml", "3", "1"."29"]]

I'm having a really hard time understanding preg_replace and I'm hoping someone might be able to help.

Is there a way to use the separating commas as guides to determine where to put the quotes?

  • 写回答

3条回答 默认 最新

  • duanjiancong4860 2015-08-17 19:20
    关注

    For a somewhat crude, but context-aware regex one could use:

    $str = preg_replace("~ [\[\],\s]*\K [^,\[\]]+ ~x", '"$0"', $str);
                               ↑             ↑
                            skip ][,    capture non-
                            + space   commas/brackets
    

    Where the charclass before \K skips structural characters, and the second […] only finds anything but commas and brackets - which then is wrapped in quotes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件