Skip to content

Instantly share code, notes, and snippets.

@WooMai
Created June 8, 2022 20:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WooMai/893956e9695523e7a8098bbc71a15deb to your computer and use it in GitHub Desktop.
Save WooMai/893956e9695523e7a8098bbc71a15deb to your computer and use it in GitHub Desktop.
Bilibili AV/BV Video ID Converter
<?php
use Exception;
/**
* Bilibili AV/BV Video ID Converter
*
* @license WTFPL
*/
class Bilibili
{
/**
* Convert AVID to BVID
*
* @author mcfx
* @link https://www.zhihu.com/question/381784377/answer/1099438784
* @license WTFPL
*
* @param int $avid
* @return string
*/
public static function av2bv(int $avid): string
{
$table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF';
$tr = [];
for ($i = 0; $i < 58; $i++) {
$tr[substr($table, $i, 1)] = $i;
}
$s = [11, 10, 3, 8, 4, 6];
$xor = 177451812;
$add = 8728348608;
$avid = ($avid ^ $xor) + $add;
$r = 'BV1 4 1 7 ';
$table_arr = str_split($table);
for ($i = 0; $i < 6; $i++) {
$r[$s[$i]] = $table_arr[floor($avid / pow(58, $i) % 58)];
}
return $r;
}
/**
* Convert BVID to AVID
*
* @author mcfx
* @link https://www.zhihu.com/question/381784377/answer/1099438784
* @license WTFPL
*
* @param string $bvid
* @return int
*/
public static function bv2av(string $bvid): int
{
$table = 'fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF';
$tr = [];
for ($i = 0; $i < 58; $i++) {
$tr[substr($table, $i, 1)] = $i;
}
$s = [11, 10, 3, 8, 4, 6];
$xor = 177451812;
$add = 8728348608;
$r = 0;
$bvid_arr = str_split($bvid);
for ($i = 0; $i < 6; $i++) {
$bvid_arr[$s[$i]];
if (!isset($bvid_arr[$s[$i]])) {
throw new Exception('Invalid BVID');
}
$r += $tr[$bvid_arr[$s[$i]]] * pow(58, $i);
}
$avid = ($r - $add) ^ $xor;
return $avid;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment