使用PHP拆分磁铁链接



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

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实现这一点?

由于parse_url()在这种情况下没有帮助,您必须使用regex来解析字符串,然后进一步操作字符串以获得跟踪器。所以类似于:

<?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];
?>

正如问题评论中所建议的,似乎有几个现有的磁链接库,您可能应该看看这些库。

然而,如果你想自己做,一种方法是为值正则表达式。让我们假设您的磁铁链接被分配给一个变量$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(),但让我们保持它的基本性。我们将使用lookbacking断言来尝试查找所需的值。

// 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)

希望这有帮助:)

相关内容

  • 没有找到相关文章

最新更新