nacho sepulveda
nacho sepulveda

Reputation: 31

How to extract a specific part from URL with PHP

I have this URL and I want to get only the URL to the part where it has an .ipa file:

http://sdl.haima.me/dl.ashx?s=8b000d38-3605-418b-8eb9-37d57f4ba24d&b=com.imagility.evergrow&v=12020&u=http%3a%2f%2fhot.haima.me%2fee%2f201702%2f1776%2fcom.imagility.evergrow_12020_20170217141048_3_fp1q5w.ipa&m=81e26501dc93bc73bec5ae8f1e7cb3c5&k=

So from that I only want this:

http%3a%2f%2fhot.haima.me%2fee%2f201702%2f1776%2fcom.imagility.evergrow_12020_20170217141048_3_fp1q5w.ipa

Then I want it to be decoded so I want to end up with:

http://hot.haima.me/ee/201702/1776/com.imagility.evergrow_12020_20170217141048_3_fp1q5w.ipa

I want this URL to be in a variable. It is part from an object within an API so accessing the first very long URL is like $jsonRoot->data->app1->ipaURL.

Upvotes: 0

Views: 65

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78984

Use a function to parse the string into variables. It will decode for you:

parse_str(parse_url($url, PHP_URL_QUERY), $vars);
echo $vars['u'];
  • Use parse_url() to get the query string
  • Use parse_str() to parse into variables in $vars
  • Access the u index in $vars

Yields:

http://hot.haima.me/ee/201702/1776/com.imagility.evergrow_12020_20170217141048_3_fp1q5w.ipa

That is assuming that the URL is found in u. If not then grep for it:

echo current(preg_grep('/\.ipa/', $vars));

Upvotes: 3

arkascha
arkascha

Reputation: 42885

Take a look at this simple demonstration:

<?php
$input = 'http://sdl.haima.me/dl.ashx?s=8b000d38-3605-418b-8eb9-37d57f4ba24d&b=com.imagility.evergrow&v=12020&u=http%3a%2f%2fhot.haima.me%2fee%2f201702%2f1776%2fcom.imagility.evergrow_12020_20170217141048_3_fp1q5w.ipa&m=81e26501dc93bc73bec5ae8f1e7cb3c5&k=';
$query = parse_url($input, PHP_URL_QUERY);
foreach (explode('&', $query) as $arg) {
    list($key, $val) = explode('=', $arg);
    if ('u'===$key) {
        echo urldecode($val);
    }
}

The output obviously is:

http://hot.haima.me/ee/201702/1776/com.imagility.evergrow_12020_20170217141048_3_fp1q5w.ipa

Upvotes: 0

Related Questions