phparrayscircular-list

Transpose the notes in a musical expression string by a nominated number of half-steps


I am trying to do chord transposition in PHP the array of Chord values are as follows:

$chords1 = array('C','C#','D','D#','E','F','F#','G','G#','A','A#','B','C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B','C');

An example would be D6/F#. I want to match the array value and then transpose it by a given number position in the array. Here is what I have so far...

function splitChord($chord){ // The chord comes into the function
    preg_match_all("/C#|D#|F#|G#|A#|Db|Eb|Gb|Ab|Bb|C|D|E|F|G|A|B/", $chord, $notes); // match the item
    $notes = $notes[0];
    $newArray = array();
    foreach($notes as $note){ // for each found item as a note
        $note = switchNotes($note); // switch the not out
        array_push($newArray, $note); // and push it into the new array
    }
    $chord = str_replace($notes, $newArray, $chord); // then string replace the chord with the new notes available
    return($chord);
}
function switchNotes($note){
    $chords1 = array('C','C#','D','D#','E','F','F#','G','G#','A','A#','B','C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B','C');
    
    $search = array_search($note, $chords1);////////////////Search the array position D=2 & F#=6
    $note = $chords1[$search + 4];///////////////////////then make the new position add 4 = F# and A#
    return($note);
}

This works, except the problem is that if I use a split chord like (D6/F#) The chord is transposed to A#6/A#. It is replacing the first note (D) with an (F#) then, Both (F#'s) with an (A#).

The question is... How can I keep this redundancy from happening. The desired output would be F#6/A#.


Solution

  • You can use preg_replace_callback function

    function transposeNoteCallback($match) {
        $chords = array('C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B', 'C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B', 'C');
        $pos = array_search($match[0], $chords) + 4;
        if ($pos >= count($chords)) {
            $pos = $pos - count($chords);
        }
        return $chords[$pos];
    }
    
    function transposeNote($noteStr) {
        return preg_replace_callback("/C#|D#|F#|G#|A#|Db|Eb|Gb|Ab|Bb|C|D|E|F|G|A|B/", 'transposeNoteCallback', $noteStr);
    }
    

    Test

    echo transposeNote("Eb6 Bb B Ab D6/F#");

    returns

    G6 C# Eb C F#6/A#