用PHP分割磁铁链接

时间:2014-04-19 00:30:06

标签: php magnet-uri

我需要一个磁铁链接中的两个项目:

magnet:?xt=urn:btih:0eb69459a28b08400c5f05bad3e63235b9853021&dn=Splinter.Cell.Blacklist-RELOADED&tr=udp%3A%2F%2Ftracker.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80&tr=udp%3A%2F%2Fopen.demonii.com%3A1337

btih的价值:

  

0eb69459a28b08400c5f05bad3e63235b9853021

和第一个udp的值:

  

udp://tracker.com:80

如何使用PHP执行此操作?

2 个答案:

答案 0 :(得分:6)

由于parse_url()在这种情况下无法帮助你必须使用正则表达式来解析字符串,然后进一步操纵字符串以获取跟踪器。如下所示:

<?php 
$string = 'magnet:?xt=urn:btih:0eb69459a28b08400c5f05bad3e63235b9853021&dn=Splinter.Cell.Blacklist-RELOADED&tr=udp%3A%2F%2Ftracker.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80&tr=udp%3A%2F%2Fopen.demonii.com%3A1337';

preg_match('#magnet:\?xt=urn:btih:(?<hash>.*?)&dn=(?<filename>.*?)&tr=(?<trackers>.*?)$#', $string, $magnet_link);

//0eb69459a28b08400c5f05bad3e63235b9853021
echo $magnet_link['hash'];

//Splinter.Cell.Blacklist-RELOADED
echo $magnet_link['filename'];

/*[trackers] => Array
(
    [0] => udp://tracker.com:80
    [1] => udp://tracker.publicbt.com:80
    [2] => udp://tracker.istole.it:6969
    [3] => udp://tracker.ccc.de:80
    [4] => udp://open.demonii.com:1337
)
*/
$magnet_link['trackers'] = explode('&', urldecode(str_replace('tr=','', $magnet_link['trackers'])));

//so to get first tracker
$magnet_link['trackers'][0];
?>

答案 1 :(得分:3)

根据问题评论中的建议,似乎有几个现有的磁力链接库 - 你应该看看这些。

但是,如果你想自己做,那么一种方法是对值进行正则表达式。我们假设您的磁力链接已分配给变量$link,如下所示:

$link ='magnet:?xt=urn:btih:0eb69459a28b08400c5f05bad3e63235b9853021&dn=Splinter.Cell.Blacklist-RELOADED&tr=udp%3A%2F%2Ftracker.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80&tr=udp%3A%2F%2Fopen.demonii.com%3A1337';

获取每个值的一种快捷方法是为每个值运行单独的preg_match() - 您可以组合两个正则表达式并运行preg_match_all()但是让它保持基本。我们将使用lookbehind断言来尝试找到所需的值。

// your magnet link
$link = 'magnet:?xt=urn:btih:0eb69459a28b08400c5f05bad3e63235b9853021&dn=Splinter.Cell.Blacklist-RELOADED&tr=udp%3A%2F%2Ftracker.com%3A80&tr=udp%3A%2F%2Ftracker.publicbt.com%3A80&tr=udp%3A%2F%2Ftracker.istole.it%3A6969&tr=udp%3A%2F%2Ftracker.ccc.de%3A80&tr=udp%3A%2F%2Fopen.demonii.com%3A1337';

// urls are encoded, let's reverse that
$link = urldecode($link); 

// first regex searches for 'btih:' and matches subsequent 
// word characters ([a-zA-Z0-9_])
// match(es) are captured as an array to $matchBtih
preg_match('/(?<=btih:)\w+/', $link, $matchBtih);

// same again, more or less, capturing word characters, colon and full-stop
// match(es) are captured as an array to $matchUdp
preg_match('/(?<=tr=)udp:\/\/[\w\:\.]+/', $link, $matchUdp);

// show results
var_dump($matchBtih, $matchUdp);

应该屈服:

array (size=1)
  0 => string '0eb69459a28b08400c5f05bad3e63235b9853021' (length=40)
array (size=1)
  0 => string 'udp://tracker.com:80' (length=20)

希望这会有所帮助:)