我正在处理播放歌曲标签的一小段代码,但是我遇到了问题。
我需要解析每个歌曲的标签行,并进行拆分,以便一方面获得大块和弦,另一方面获得单词。
每个块就像:
$line_chunk = array(
0 => //part of line containing one or several chords
1 => //part of line containing words
);
他们应该保持“分组”状态。我的意思是,仅当函数达到和弦与单词之间的“极限”时,才应拆分。
我想我应该使用preg_split实现此目的。我进行了一些测试,但是我只能在和弦上进行拆分,而不能对和弦进行“分组”:
$line_chunks = preg_split('/(\[[^]]*\])/', $line, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
这些示例向您展示了我想要得到的:
在不包含和弦的线上:
$input = '{intro}';
$results = array(
array(
0 => null,
1 => '{intro}
)
);
在仅包含和弦的线上:
$input = '[C#] [Fm] [C#] [Fm] [C#] [Fm]';
$results = array(
array(
0 => '[C#] [Fm] [C#] [Fm] [C#] [Fm]',
1 => null
)
);
在同时包含以下内容的行上:
$input = '[C#]I’m looking for [Fm]you [G#]';
$results = array(
array(
0 => '[C#]',
1 => 'I’m looking for'
),
array(
0 => '[Fm]',
1 => 'you '
),
array(
0 => '[G#]',
1 => null
),
);
有关如何执行此操作的任何想法?
谢谢 !
preg_split
不是要走的路。在大多数情况下,当您要完成复杂的拆分任务时,尝试匹配您感兴趣的内容比尝试使用不容易定义的分隔符进行拆分更容易。
一个preg_match_all
办法:
$pattern = '~ \h*
(?| # open a "branch reset group"
( \[ [^]]+ ] (?: \h* \[ [^]]+ ] )*+ ) # one or more chords in capture group 1
\h*
( [^[\n]* (?<=\S) ) # eventual lyrics (group 2)
| # OR
() # no chords (group 1)
( [^[\n]* [^\s[] ) # lyrics (group 2)
) # close the "branch reset group"
~x';
if (preg_match_all($pattern, $input, $matches, PREG_SET_ORDER)) {
$result = array_map(function($i) { return [$i[1], $i[2]]; }, $matches);
print_r($result);
}
分支重置组为每个分支保留相同的组编号。
注意:随时添加:
if (empty($i[1])) $i[1] = null;
if (empty($i[2])) $i[2] = null;
如果要获取空项目而不是空项目,请在地图函数中输入。
注意2:如果逐行工作,可以\n
从花样中删除。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句