2017-05-10 36 views
0

Spotify有兩種使用url /標識符的方法。我想要得到的字符串的最後部分下方(標識)獲取具有多個preg_match的字符串的最後部分

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

ID的長度總是一樣嗎? –

+0

我這麼認爲。無法在任何Spotify文檔中找到它。編輯:我發現這個:你可以在Spotify URI的末尾找到一個base-62標識符(見上文),用於藝術家,曲目,專輯,播放列表等。 – KJS

回答

1

試試這個爲有斜線的網址。如果Spotify的字符串使用冒號(:)簡單地切換/: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'

$id3 = false

+0

聰明!但是如果代碼之後還有更多呢?像斜線和更多的數據?這就是爲什麼我想獲得ID後面的ID或/ – KJS

+0

@KJS提供和示例,以便我能夠看到你的意思。 –

+0

這會是這樣的:https://play.spotify.com/artist/6mdiAmATAx73kdxrNrnlao/extra-url-seo-nonsense – KJS

相關問題