該函數是一段將歌詞文件轉換爲SRT字幕文件的PHP代碼。具體實現過程如下:
- 去除多餘的空白行,使用正則表達式
preg_replace("/^\s*$/m", "", $lrc)。 - 將歌詞文本按行分割,使用
explode("\n", $lrc)。 - 循環每一行歌詞內容,使用正則表達式
preg_match_all("/\[(\d{2}):(\d{2})(?:\.(\d{2,3}))?\]/", $lines[$i], $matches)匹配時間標籤和歌詞內容。 - 如果匹配到時間標籤,則獲取開始時間和結束時間。其中,若歌詞內容直接跟在最後一個時間標籤之後的情況,需要根據下一行的時間標籤計算結束時間;否則,將結束時間設爲開始時間+5秒。
- 根據開始和結束時間以及歌詞內容構建SRT字幕內容,並將其存入
$srt字符串中。 - 返回
$srt字符串。
這個函數的主要作用是將 LRC 格式的歌詞轉換爲 SRT 格式的字幕,以便於在視頻播放器中顯示歌詞。
代碼:
function lrc2srt($lrc) {
// print_r($lrc);
// 去除多餘的空白行
$lrc = preg_replace("/^\s*$/m", "", $lrc);
// 按行分割
$lines = explode("\n", $lrc);
$count = count($lines);
// print_r($lines);
$srt = '';
$index = 1;
for ($i = 0; $i < $count; $i++) {
// 匹配時間標籤和歌詞內容
preg_match_all("/\[(\d{2}):(\d{2})(?:\.(\d{2,3}))?\]/", $lines[$i], $matches);
// print_r($matches);
if (!empty($matches[0])) {
// 獲取時間標籤
$startHour = intval($matches[1][0]);
$startMinute = intval($matches[2][0]);
$startSecond = intval($matches[3][0]);
// $startTime = sprintf("%02d:%02d:%02d,%03d", 0,$startHour, $startMinute, $startSecond);
$startTime = sprintf('%02d:%02d:%02d,%03d', 0, $startHour, $startMinute, $startSecond * 10);
// 獲取歌詞內容
if (strpos($lines[$i], ']') === false) {
// 特殊情況:歌詞內容直接跟在最後一個時間標籤之後的情況
$lyric = trim(substr($lines[$i], strlen($matches[0][0])));
if ($i < $count - 1 && strpos($lines[$i + 1], '[') !== false) {
// 下一行是新的時間標籤,計算結束時間
preg_match_all("/\[(\d{2}):(\d{2})(?:\.(\d{2,3}))?\]/", $lines[$i + 1], $nextMatches);
$endHour = intval($nextMatches[1][0]);
$endMinute = intval($nextMatches[2][0]);
$endSecond = intval($nextMatches[3][0]);
} else {
// 下一行無新的時間標籤,將結束時間設爲開始時間+5秒
$endHour = $startHour;
$endMinute = $startMinute;
$endSecond = $startSecond + 5;
}
} else {
$lyric = trim(preg_replace("/\[(\d{2}):(\d{2})(?:\.(\d{2,3}))?\]/", "", $lines[$i]));
// 獲取下一行的時間標籤
preg_match_all("/\[(\d{2}):(\d{2})(?:\.(\d{2,3}))?\]/", $lines[$i + 1], $nextMatches);
if (!empty($nextMatches[0])) {
// 計算結束時間
$endHour = intval($nextMatches[1][0]);
$endMinute = intval($nextMatches[2][0]);
$endSecond = intval($nextMatches[3][0]);
} else if ($i !== $count - 1) {
// 下一行無時間標籤,將結束時間設爲開始時間+5秒
$endHour = $startHour;
$endMinute = $startMinute;
$endSecond = $startSecond + 5;
}
}
// 計算結束時間
// $endTime = sprintf("%02d:%02d:%02d,%03d", 0, $endHour, $endMinute, $endSecond);
$endTime = sprintf('%02d:%02d:%02d,%03d', 0, $endHour, $endMinute, ($endSecond - 5) * 10);
if(!empty($lyric)){
// 構建SRT字幕內容
$srt .= $index . "\n";
$srt .= $startTime . ' --> ' . $endTime . "\n";
$srt .= $lyric . "\n\n";
$index++;
}
}
}
return $srt;
}
}