John Doe
John Doe

Reputation: 143

Exploding a url in PHP

How can I obtain just the ID portion of this url.

281805943&buying=true&liking=false&download=true&sharing=false&show_artwork=false&hide_related=true&show_comments=false&show_playcount=false&show_user=false&color=e55b5b&color_theme=f5f5f5&auto_play=

I currently have exploded the url which contained the API path + the actual link but trying to obtain the ID 281805943 has proven to be a little harder, please note that we can't just echo out 281805943 because I am scraping a website and gathering their urls, this id will be different every time how ever the format will remain the same.

Original URL format looks like the following.

https://w.soundcloud.com/player/?url=https://api.soundcloud.com/tracks/281805943&buying=true&liking=false&download=true&sharing=false&show_artwork=false&hide_related=true&show_comments=false&show_playcount=false&show_user=false&color=e55b5b&color_theme=f5f5f5&auto_play=

I've currently exploded it using this

$d2 = $dl->src;
$test = explode("/", $d2);
$test[8];

Upvotes: 2

Views: 1437

Answers (4)

Robert Wade
Robert Wade

Reputation: 5003

Assuming your ID is always between 'tracks/' and '&amp':

$url = 'https://w.soundcloud.com/player/?url=https://api.soundcloud.com/tracks/281805943&buying=true&liking=false&download=true&sharing=false&show_artwork=false&hide_related=true&show_comments=false&show_playcount=false&show_user=false&color=e55b5b&color_theme=f5f5f5&auto_play=';

$pattern = "/(tracks\/)([\d]+)(\&amp)/";
preg_match($pattern,$url,$matches,PREG_OFFSET_CAPTURE);

var_dump($matches[2][0]);

Upvotes: 2

Peter Featherstone
Peter Featherstone

Reputation: 8102

If the format is always exactly the same then you can do the below using the $test[8] variable you already have:

parse_str($test[8], $output);
$id = key($output);

Or a single liner:

$id = explode('&', $test[8])[0];

There are many ways to skin a cat

Upvotes: 1

Professor Abronsius
Professor Abronsius

Reputation: 33804

Not exactly pretty but it does find the id

$url="https://w.soundcloud.com/player/?url=https://api.soundcloud.com/tracks/281805943&buying=true&liking=false&download=true&sharing=false&show_artwork=false&hide_related=true&show_comments=false&show_playcount=false&show_user=false&color=e55b5b&color_theme=f5f5f5&auto_play=";
preg_match('@/tracks/(\d+)&@',$url,$matches);
echo 'id='.$matches[1];

Upvotes: 2

Duane Lortie
Duane Lortie

Reputation: 1260

Sounds like a job for parse_url, from the PHP docs....

<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));
$blob = parse_url($url, PHP_URL_PATH);
echo $blob['query'];  //arg=value
echo $blob['anchor'];  //anchor

Upvotes: 2

Related Questions