You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何从特定字符截取动态字符串并保留剩余部分

Extract Valid JSON from a Response with Unwanted Prefix Text

Let's get that JSON parsing sorted out for you! The issue here is that your raw response includes extra prefix text before the actual JSON content, and your initial attempt with substr() and strpos() likely had the parameters misused. Here's how to fix it properly:

Step-by-Step Solution

  1. Locate the start of the JSON: Find the position of the first opening curly brace { in your raw response string. This marks where the valid JSON begins.
  2. Extract the JSON substring: Use substr() to take everything from that starting position to the end of the string.
  3. Parse the clean JSON: Now you can safely use json_decode() on the cleaned string.

Example Code

// Your raw response string
$rawResponse = "http code:200 Output:{ \"QueryResponse\" : { \"Header\" : { \"DateTime\" : \"2019-04-16T07:24:41.718Z\", \"MessageID\" : \"1111111111111111111111\" }, } }";

// Find the position of the first "{"
$jsonStartIndex = strpos($rawResponse, '{');

// Check if we found the JSON start to avoid errors
if ($jsonStartIndex !== false) {
    // Extract the valid JSON part
    $cleanJsonString = substr($rawResponse, $jsonStartIndex);
    
    // Parse the JSON into an array
    $parsedData = json_decode($cleanJsonString, true);
    
    // Verify the result (optional)
    print_r($parsedData);
} else {
    // Handle the case where no JSON was found in the response
    echo "Error: No valid JSON content detected in the response.";
}

Why This Works

  • strpos($rawResponse, '{') returns the numerical index of the first occurrence of { in the string. If no { is found, it returns false, which we check for to prevent invalid substrings.
  • substr($rawResponse, $jsonStartIndex) starts at the found index and captures all remaining characters in the string—this gives you the complete, valid JSON you need for parsing.

This approach will reliably strip off any prefix text before the JSON, even if the prefix (like "http code:200 Output:") varies slightly in length or content, as long as the JSON starts with {.

内容的提问来源于stack exchange,提问作者Mr-Faizan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:35:54