I'm loosing my hairs trying to figure out how to parse a music (text) tab using preg_match_all and PREG_OFFSET_CAPTURE.
Example input :
[D#] [G#] [Fm]
[C#] [Fm] [C#] [Fm] [C#] [Fm]
[C]La la la la la la [Fm]la la la la [D#]
[Fm]I made this song Cause I [Bbm]love you
[C]I made this song just for [Fm]you [D#]
[Fm]I made this song deep in [Bbm]my heart
The output I'm trying to get :
D# G# Fm
C# Fm C# Fm C# Fm
C Fm D#
La la la la la la la la la la
Fm Bbm
I made this song Cause I love you
C Fm D#
I made this song just for you
Fm Bbm
I made this song deep in my heart
And in the end, I want to wrap the chords with html tags.
Notice that the spaces between chords should match exactly the position of those chords in the original input.
I started to parse the input line by line, detect chords, get their position, ... but my code is not working... There something that's wrong in my function line_extract_chords, it works not as it should.
Any ideas ?
<style>
body{
font-family: monospace;
white-space: pre;
</style>
<?php
function parse_song($content){
$lines = explode(PHP_EOL, $content); //explode lines
foreach($lines as $key=>$line){
$chords_line = line_extract_chords($line);
$lines[$key] = implode("\n\r",(array)$chords_line);
}
return implode("\n\r",$lines);
}
function line_extract_chords($line){
$line_chords = null; //text line with chords, used to compute offsets
$line_chords_html = null; //line with chords links
$found_chords = array();
$line = html_entity_decode($line); //remove special characters (would make offset problems)
preg_match_all("/\[([^\]]*)\]/", $line, $matches, PREG_OFFSET_CAPTURE);
$chord_matches = array();
if ( $matches[1] ){
foreach($matches[1] as $key=>$chord_match){
$chord = $chord_match[0];
$position = $chord_match[1];
$offset= $position;
$offset-= 1; //left bracket
$offset-=strlen($line_chords); //already filled line
//previous matches
if ($found_chords){
$offset -= strlen(implode('',$found_chords));
$offset -= 2*(count($found_chords)); //brackets for previous chords
}
$chord_html = '<a href="#">'.$chord.'</a>';
//add spaces
if ($offset>0){
$line_chords.= str_repeat(" ", $offset);
$line_chords_html.= str_repeat(" ", $offset);
}
$line_chords.=$chord;
$line_chords_html.=$chord_html;
$found_chords[] = $chord;
}
}
$line = htmlentities($line); //revert html_entity_decode()
if ($line_chords){
$line = preg_replace('/\[([^\]]*)\]/', '', $line);
return array($line_chords_html,$line);
}else{
return $line;
}
}
?>