0

I need to parse the id from the following string:

 https://itunes.apple.com/us/album/24k-magic/id1161503945?i=1161504024&uo=2

I need to only return the following:

id1161503945

The string always begins with https://itunes.apple.com/ and ends with ?i=#####&uo=2

I tried string and replace with wildcards but that did not work.

2 Answers 2

1

Well, you can use this below regex. It is working. I have use preg_replace function.

$data = 'https://itunes.apple.com/us/album/24k-magic/id1161503945?i=1161504024&uo=2';
echo preg_replace("/(.*)\/(\w+)\?(.*)/","$2",$data);

Output is

id1161503945

Or You can use

 preg_match("/(\/)(\w+)(\?)/",$data,$m);

 echo $m[2];

Same output.

Hope it help you

Sign up to request clarification or add additional context in comments.

Comments

1

If it's really always the last element (before query params) in the url, then you can use this simple regex:

'/id[^?]+/'

CAUTION: as pointed by @xhienne, this works only if you're sure that another id string doesn't appear anywhere before the searched part.
If it may happen, rather use:

'/id[\d]+/'

This way, it's safe with respect to a previous id string, but the searched id must be followed by digits only.

8 Comments

I tested it and it returns "1" withought the quotes
@JohnDenver Seems that you take the "returned" value from preg_match! Assuming $url is your tested url, write preg_match('/id[^?]+/', $url, $match);. Then the expected result is in $match[0].
That would rather be '/id[0-9]+/', else you are likely to match the album name, like in itunes.apple.com/us/album/id-look-good-on-you-single/…
@xhienne I don't understand what you mean. [^?]+ accepts any id (even if not only digits), and stops before query params, if any.
@cFreed See the URL I gave. Your regex would yield id-look-good-on-you-single/id1094054642. An iTunes id always ends with digits (after "id"). The id is the last part of the URL, after / and before a possible query. These conditions have to be included in the regex (mine is incomplete in this regard)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.