0

我正在尝试在 PHP 中进行和弦换位,弦值数组如下...

$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');

一个例子是D6/F#。我想匹配数组值,然后将其转置为数组中给定的数字位置。这是我到目前为止...

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);
}

这行得通,除了问题是,如果我使用像(D6/F#)这样的分裂和弦,则和弦被移调到 A#6/A#。它将第一个音符 (D) 替换为 (F#),然后将两个 (F#'s) 替换为 (A#)。

问题是......我怎样才能防止这种冗余发生。所需的输出将是F#6/A#。感谢您的帮助。如果解决方案已发布,我会将其标记为已回答。

4

2 回答 2

1

便宜的建议:进入自然数域 [ [0-11]] 并仅在显示时将它们与相应的注释相关联,它将为您节省很多时间。

唯一的问题是同音异音[例如升C/降D],但希望你能从音调中推断出来。

于 2012-09-29T18:34:35.823 回答
1

您可以使用 preg_replace_callback 函数

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);
}

测试

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

返回

G6 C# Eb CF#6/A#

于 2012-09-29T18:35:11.117 回答