Hongmu Notes
Home Language Notes Convert text-based lyrics into HTML-format lyrics.
Language Notes PHP

Convert text-based lyrics into HTML-format lyrics.

Convert text-based lyrics into HTML-format lyrics.

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!

The final code is:

 隐藏内容:付费阅读
public function diaoMaoC($str){
	$array = explode("\n",$str);
	if(empty($array) || strpos($str,"\n") === false){
		return $this->diaoMaoLyric($str);
	}else{
		foreach ($array as $v){
			preg_match_all('/\[(\d{2}:\d{2}(.\d{2,})?)\]/',$v,$matchs);
			if(!empty($matchs[1])){
				foreach ($matchs[1] as $v2){
					$timeData[] = $v2;
				}
			}else{
				return $this->diaoMaoLyric($str);
			}
		}
		sort($timeData);
		foreach ($timeData as $v){
			foreach ($array as $v2) {
				if (strpos($v2, $v) !== false) {
					$html .= '<p data-time="' . $v . '">' . preg_replace('/\[(\d{2}:\d{2}(.\d{2,})?)\]/','',$v2) . '</p>';
					break;
				}
			}
		}
		return $html;
	}
	
}

public function diaoMaoLyric($str){
	// 替换[]内的内容
	$str = preg_replace('/\[[^\]]+\]/', '', $str);
	
	// 将换行符替换为中文逗号
	$str = str_replace("\n", '</p><p>', $str);
	$str = str_replace('\n', '</p><p>', $str);
	
	$str = "<p>".$str."</p>";
	
	$str = str_replace("<p></p>", '', $str);
	
	return $str;
}

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 143
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 191
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

(Adaptive mobile version) Responsive image display – PBootCMS website template (1023)

(Adaptive mobile version) Responsive image display – PBootCMS website template (1023) Practical Collection pbootcms Template

A responsive image display PbootCMS website template compatible with both PC and WAP devices. Featuring a visually artistic design style, this template is ideal for photographers, designers, and galleries showcasing their portfolios or photographic works. It enables visual creatives to present their work online and attract clients and followers. Template Overview | Installation Instructions | Website Admin Panel: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn
👁 51
(Adaptive mobile version) Responsive, universal website template for pharmaceutical and pharmaceutical companies; Download HTML5 agricultural and landscaping website source code – 0319

(Adaptive mobile version) Responsive, universal website template for pharmaceutical and pharmaceutical companies; Download HTML5 agricultural and landscaping website source code – 0319 Practical Collection pbootcms Template

An adaptive, responsive, universal corporate website template for pharmaceutical and agricultural landscaping businesses, built with HTML5 technology. Its fresh and professional design makes it ideal for pharmaceutical companies or agricultural enterprises to showcase their products and capabilities. It is an ideal foundational choice for companies in the pharmaceutical, healthcare, or agriculture sectors to create their official websites. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www...
👁 55
After clicking to submit the form in Empire CMS, use js to combine the URL and redirect it

After clicking to submit the form in Empire CMS, use js to combine the URL and redirect it Program Notes Empire cms Language Notes JavaScript

Many times, the search link is too long and carries many parameters. We want to make pseudo-static modifications and also hope that the link can be accessed a second time. Original html code: 🔒 Hidden content: You can view it after logging in &lt;form class="form-search" id="q-form" method="get"&gt; &lt;div class="input-…
👁 304
acupuncture treatment

acupuncture treatment Hobbies Memo notes

Acupuncture treatment of the head General headache: Baihui point (nearly selected), Yongquan point Migraine: Hegu on the contralateral side, Taiyanggu on the ipsilateral side Nausea and vomiting: Zhongwan, Neiguan, Zusanli, Gongsun Post-auricular pain: First pain: Tianjing Long-term pain: Zhongzhu Forehead pain: Zhongwan point Eyebrow bone pain: one inch below the contralateral Yinlingquan Pain in the back of the head: Tianzhu First pain: Shugu point Long-term pain: Weizhong point. Brain tumor: whole body shakes, trembles, and spasms. Prescription (Whole Scorpion, Centipede) to calm wind and relieve spasm. Next...
👁 233
Computer Operating System Software Download Website Template 0573

Computer Operating System Software Download Website Template 0573 Practical Collection Yiyou template

An EYO CMS website template designed for hosting computer operating systems and software downloads. Its professional design style is ideal for showcasing operating systems, software applications, download services, and technical news, helping software resource platforms attract technical users online. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EYO CMS | EYO CMS (Eyo...
👁 55
(Adaptive mobile version) PBootCMS template for corporate consulting management websites; Download source code for financial service institution websites – 1024

(Adaptive mobile version) PBootCMS template for corporate consulting management websites; Download source code for financial service institution websites – 1024 Practical Collection pbootcms Template

A PbootCMS website template for corporate consulting management, compatible with both PC and WAP devices. Its professional and sophisticated design makes it ideal for management consulting firms and financial institutions to showcase their service offerings and brand strength. This template helps professional service providers attract corporate clients online and expand their business. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 59