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
- 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. - Extract the JSON substring: Use
substr()to take everything from that starting position to the end of the string. - 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 returnsfalse, 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
相关产品推荐
相关产品推荐

