Spotify有两种使用url / identifier的方法。我想得到下面字符串的最后一部分(ID)
example url's:
a. https://play.spotify.com/artist/6mdiAmATAx73kdxrNrnlao
b. spotify:artist:6mdiAmATAx73kdxrNrnlao
无法让下面的代码生效,所以我稍后也可以添加更多选项。我首先尝试使用basename,但显然这不适用于':'。
$str = "https://play.spotify.com/artist/6mdiAmATAx73kdxrNrnlao";
or:
$str = "spotify:artist:6mdiAmATAx73kdxrNrnlao";
if (
preg_match('artist/([a-zA-Z0-9]{22})/', $str, $re) ||
preg_match('artist:([a-zA-Z0-9]{22})/', $str, $re)
) {
$spotifyId = $re[1];
}
感谢任何帮助!
答案 0 :(得分:1)
尝试使用斜杠的网址。如果Spotify字符串使用冒号($("#input").keydown(function (e) {
if (e.which == 13) {
alert("enter pressed");
return false;
}
});
),只需将:
切换为/
函数中的:
:
explode()
有用功能的粗略示例如下:
// your url
$url = "https://play.spotify.com/artist/6mdiAmATAx73kdxrNrnlao/blah/blah/blah";
// get path only
$path = parse_url($url)['path'];
// seperate by forward slash
$parts = explode('/', $path);
// go through them and find string with 22 characters
$id = '';
foreach ($parts as $key => $value) {
if (strlen($value) === 22 ) {
// found it, now store it
$id = $value;
break;
}
}
结果:
function getSpotifyId($spotifyUrl) {
// check for valid url
if (!filter_var($spotifyUrl, FILTER_VALIDATE_URL)) {
// split using colon
$parts = explode(':', parse_url($spotifyUrl)['path']);
} elseif (filter_var($spotifyUrl, FILTER_VALIDATE_URL)) {
// split using forward slash
$parts = explode('/', parse_url($spotifyUrl)['path']);
}
// loop through segments to find id of 22 chars
foreach ($parts as $key => $value) {
// assuming id will always be 22 characters
if (strlen($value) === 22 ) {
// found it, now return it
return $value;
}
}
return false;
}
$id1 = getSpotifyId('http://localhost/xampp/web_development/6mdiAmATAx73kdxrNrnlao/stack.php');
$id2 = getSpotifyId('spotify:artist:6mdiAmATAx73kdxrNrnlao');
$id3 = getSpotifyId('My name is tom');
$id1 = '6mdiAmATAx73kdxrNrnlao'
$id2 = '6mdiAmATAx73kdxrNrnlao'