【问题标题】:How to remove "" from json string [closed]如何从json字符串中删除“”[关闭]
【发布时间】:2020-03-01 14:40:57
【问题描述】:

我想从字符串外部删除双引号(“”)。

我有以下字符串。

$p = "{\"match\":\"https:\/\/mong.com\/sddaad\",\"type\":\"exact\",\"activated\":\"True\"}"

我希望结果是这样的:

$p = {\"match\":\"https:\/\/mong.com\/sddaad\",\"type\":\"exact\",\"activated\":\"True\"}

我认为展示强大的代码是一个很好的问题,我不明白为什么人们投票反对我并结束我的问题。离得近的一定不知道最佳答案!!!

【问题讨论】:

  • 因为我想以这种格式将json数据保存在我的数据库中。
  • json_decode:$p = json_decode("{\"match\":\"https:\/\/mong.com\/sddaad\",\"type\":\"exact\",\"activated\":\"True\"}")
  • 不工作
  • 查看答案,你会看到更多细节
  • 你可以使用trim方法去掉""。

标签: php json laravel


【解决方案1】:

我认为你很困惑。您想删除字符串外部的双引号,但实际上这只是字符串的定义。

如果你简单的echo你的值,你会看到你想要删除的双引号无论如何都不存在。

Json 通常作为字符串处理,因此应将其括在引号中。重要的是要使用它的 json 格式。

【讨论】:

    【解决方案2】:

    检查一下,
    您可以 json_decode 然后使用 JSON_UNESCAPED_SLASHES 进行编码

    $p = "{\"match\":\"https:\/\/mong.com\/sddaad\",\"type\":\"exact\",\"activated\":\"True\"}";
    echo json_encode(json_decode($p),JSON_UNESCAPED_SLASHES);
    

    Demo

    您可以毫无问题地将输出保存到数据库中,也可以使用 json_decode 读取。

    输出

    {"match":"https://mong.com/sddaad","type":"exact","activated":"True"}
    

    【讨论】:

      【解决方案3】:

      我不确定你想达到什么目的,但你可能想看看trim 方法

      $string = "sample text"
      
      trim($string, '"')
      

      trim 删除字符串开头和结尾的指定字符。如果没有指定表达式,则删除空格

      【讨论】:

      • 在您的示例中不会做任何事情," 是字符串分隔符
      • @N69S 我知道吗?
      【解决方案4】:

      您可以使用 PHP 函数 addlashes() 使其工作。

      <?php 
      $json_array = array(
      'title' => 'I love Dexter series this is a test\'s with "special" characters'
      );
      
      echo $json_decode =addslashes(json_encode($json_array));
      
      ?> 
      

      输出:{\"title\":\"我喜欢 Dexter 系列这是一个带有 \\"special\\" 个字符的测试\"}

      【讨论】:

      • 他想删除{..}之外的",它们是字符串分隔符,trim 不会这样做。
      • 它不工作
      • 请查看更新后的答案
      【解决方案5】:

      你需要做的是把它保存在 laravel 的一个 json 字段中,把你的字符串解码成一个数组,然后将你的属性值设置为那个数组。

      $p = "{\"match\":\"https:\/\/mong.com\/sddaad\",\"type\":\"exact\",\"activated\":\"True\"}"
      $value = json_decode($p, true); //second parameter to get the result as an associative array
      $user->properties = $value;
      $user->save();
      

      不要忘记在模型类中设置该属性的演员表

      class User extends Model
      {
          protected $casts = [
              'properties' => 'array'
          ];
      

      【讨论】:

        【解决方案6】:

        $p= preg_replace('/"([a-zA-Z]+[a-zA-Z0-9_]*)":/','$1:',$p);

        【讨论】:

          猜你喜欢
          • 2021-03-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-25
          • 1970-01-01
          • 2012-10-02
          • 1970-01-01
          相关资源
          最近更新 更多