Lyrics to be converted:
[01:04.81] 你好
[02:57.54][00:42.86]真情像草原广阔
[03:04.81][00:50.07]层层风雨不能阻隔
[05:04.81] 叼毛Converted result:
<p data-time="01:04.81">你好</p>
<p data-time="00:42.86">真情像草原广阔</p>
<p data-time="00:50.07">层层风雨不能阻隔</p>
<p data-time="02:57.54">真情像草原广阔</p>
<p data-time="03:04.81">层层风雨不能阻隔</p>
<p data-time="05:04.81">叼毛</p>I've tried countless methods—but Regular Expressions are just too tough!
In the end, I ended up implementing it using a `foreach` loop combined with regular expression matching – I really racked my brain over this for an entire day!
The initial code is:
<?php
// 假设歌词文本保存在 $lyrics 变量中
// 正则匹配出所有时间戳,并将它们以升序排列
preg_match_all('/\[(\d{2}:\d{2}\.\d{2})\]/', $lyrics, $matches);
$timestamps = $matches[1];
sort($timestamps);
// 根据时间戳将歌词内容拆分成数组
$lyric_lines = preg_split('/\[\d{2}:\d{2}\.\d{2}\]/', $lyrics);
array_shift($lyric_lines);
// 将时间戳和歌词内容对应起来,输出 HTML 标签
for ($i = 0; $i < count($timestamps); $i++) {
$time = $timestamps[$i];
$lyric = trim($lyric_lines[$i]);
echo '<p data-time="' . $time . '">' . $lyric . '</p>';
}
?>However, there is one issue: if the lyrics contain two time markers [03:04.81][00:50.07], it can lead to problematic matching!
Furthermore, some lyrics contain multiple instances of this time pattern; therefore, using regular expressions requires multiple processing steps!
Since it's impossible to predict how many times the occurrence time will appear or how many times the lyrics will loop, I used `for-each` to implement this!