dpwo36915 2017-12-13 11:51
浏览 297

如何使PHP json_decode接受单引号中的参数?

I have a list of params that I get from a specific shortcode I made available for users to provide.

Example of user input: This is my list of names: {{names("John", 'Mike', "O'connor")}}

From that, I have a regex to extract the list of params, so I get a string like: "John", 'Mike', "O'connor"

But now I need to convert this list to an array and the best way I can think is using json_decode, which can break as some users simply use single quotes.

What's the best way to convert this string into an array? Using str_replace to replace ' by " will also break the ' in the "O'connor" param.

  • 写回答

1条回答 默认 最新

  • duangao7133 2017-12-13 12:27
    关注

    What about extracting the names with regex like below?

    $re = '/(["\'])((?:(?!\1).)*)\1/';
    $str = '{{names("John", \'Mike\', "O\'connor")}}';
    
    preg_match_all($re, $str, $matches, PREG_PATTERN_ORDER, 0);
    
    // Print the entire match result
    var_dump($matches);
    

    Outputs:

    array (size=3)
      0 => 
        array (size=3)
          0 => string '"John"' (length=6)
          1 => string ''Mike'' (length=6)
          2 => string '"O'connor"' (length=10)
      1 => 
        array (size=3)
          0 => string '"' (length=1)
          1 => string ''' (length=1)
          2 => string '"' (length=1)
      2 => 
        array (size=3)
          0 => string 'John' (length=4)
          1 => string 'Mike' (length=4)
          2 => string 'O'connor' (length=8)
    

    The names are available at $matches[0]with quotes or at $matches[2] without quotes.

    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等