【问题标题】:How to cut a dynamic string from specific character and keep the remaining part in a variable如何从特定字符中剪切动态字符串并将剩余部分保存在变量中
【发布时间】:2019-04-19 07:57:07
【问题描述】:

我想要一个 json_decode 一个需要特定格式的字符串,但我的字符串包含一些额外的文本,所以我想剪切一些不固定的字符串部分。我想从“{”的特定字符中删除。那我怎么剪掉那个文本呢。

我尝试了这两个函数 substr() 和 strpos() 但这些函数返回我想要删除的字符串。从这里PHP Cut String At specific character .

$responseArray = http_post_with_status_code($url, $post_string, "application/json", false, $options);

        $rawResponse = $responseArray['message'];

// This is the expected output of $rawResponse.

 $rawResponse = http code:200 Output:{
  "QueryResponse" : {
    "Header" : {
      "DateTime" : "2019-04-16T07:24:41.718Z",
      "MessageID" : "1111111111111111111111"
    },
  }
}

没有这些字符的字符串(http 代码:200 输出:)

【问题讨论】:

  • 请考虑使用 PHP 的 JSON API。
  • 丑陋的方式,但它应该可以工作:$response = json_decode(str_replace('http code:200 Output:', '', $rawResponse));

标签: php string


【解决方案1】:

我想你要找的函数是strstr

这应该可以解决问题:

strstr($rawResponse, '{');

【讨论】:

    【解决方案2】:

    您可以通过使用strpos() & substr()来实现您的目标

    解决办法如下:

    if (strpos($rawResponse, "{")) {
        $index = strpos($rawResponse, "{");
        echo substr($rawResponse, $index);
    } else {
        echo "'{' this character not found!";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      相关资源
      最近更新 更多