Extract URL from an string retreived by API with backwards slashes

So I am retrieving an URL from an API (from wordpress), however the URL I get has backwards slashes and I am not managing to extract the URL from the string so I can parse it this is what the received API string looks like:

string(93) "{"url":"https://api.mysite.com/downloads/?h=153dcf3eca49a51&d=123332221"}"

And I need to get the hash key after the query ?h=

153dcf3eca49a51&d=123332221

However I am having a pretty hard time, I have tried stripslashes() and Regex but the string is obtained from an array and I am not being able to figure it out.

This is how the URL is obtained:

function get_api_data() {


$url = "https://api.mysite.com/?access_token=1234567";


$arguments = array(
    'method' => 'POST',

$response = wp_remote_post( $url, $arguments );

if ( is_wp_error( $response ) ) {
    $error_message = $response->get_error_message();
    return "Something went wrong: $error_message";
} else {
    echo '<pre>';
    var_dump( wp_remote_retrieve_body( $response ) );
    echo '</pre>';
}

What would be the best practice for cleaning the entire string and only obtaining the hash key?

Answer

Using the functions that are purpose built for each task:

$response = wp_remote_retrieve_body($response);
parse_str(parse_url(json_decode($response, true)['url'], PHP_URL_QUERY), $result);
echo $result['h'];
  • Decode the JSON string into a PHP array json_decode($response, true) and then access the url element ['url']:
    • Array ( [url] => https://api.mysite.com/downloads/?h=153dcf3eca49a51&d=123332221 )
  • Parse that URL with parse_url to get the query string PHP_URL_QUERY:
    • h=153dcf3eca49a51&d=123332221
  • Parse the query string with parse_str into an array $result of variables and values and access the h element:
    • Array ( [h] => 153dcf3eca49a51 [d] => 123332221 )

Leave a Reply

Your email address will not be published. Required fields are marked *