Search code examples
phpregexjsonparse-url

PHP: Stripping protocol from Instagram API image urls


This is a snippet from an Instagram JSON:

"images":{
    "standard_resolution":
        { "url":"http:\/\/scontent-a.cdninstagram.com\/hphotos-xfa1\/t51.2885-15\/10593467_370803786404217_1595289732_n.jpg","width":640,"height":640}
}

I'd like to strip the protocol from ['images']['standard_resolution']['url']. I tried with:

.parse_url($value['images']['standard_resolution']['url'], PHP_URL_HOST) . parse_url($value['images']['standard_resolution']['url'], PHP_URL_PATH).

But does nothing! I think it has to do with the / escaping done in JSON (http:\/\/). Because if I try

.parse_url("http://www.google.com", PHP_URL_HOST) . parse_url("http://www.google.com", PHP_URL_PATH).

.. it just works fine. I'd like to keep things easy.. and don't use regex. parse_url would be perfect.


Solution

  • Why would you even need to do a replace or regex at all?

    If you use json_decode the escaped slashes are un-escaped.

    So doing like this:

    <?php
    
    $foo = '{"images":{"standard_resolution":{"url":"http:\/\/scontent-a.cdninstagram.com\/hphotos-xfa1\/t51.2885-15\/10593467_370803786404217_1595289732_n.jpg","width":640,"height":640}}}';
    $bar = json_decode($foo, true);
    
    $baz = 
    parse_url($bar['images']['standard_resolution']['url'], PHP_URL_HOST) . 
    parse_url($bar['images']['standard_resolution']['url'], PHP_URL_PATH);
    
    echo $baz;
    

    Would output:

    scontent-a.cdninstagram.com/hphotos-xfa1/t51.2885-15/10593467_370803786404217_1595289732_n.jpg
    

    See:

    http://ideone.com/F0c4m9