php-字符串替换

php-字符串替换,php,Php,我正在尝试在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 co

我正在尝试在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)都替换为一个(A)


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

廉价建议:进入自然数域[
[0-11]
]并仅在显示时将其与相应注释关联,这将节省您很多时间


唯一的问题是同音字的发音[例如C-sharp/D-flat],但希望你能从音调中推断出来。

你可以使用preg\u replace\u回调函数

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

回声转置信号(“Eb6 Bb B Ab D6/F#”)

返回


G6 C#Eb C F#6/A#

如何将变量添加到数字的回调中。。。我不明白这个问题。你想同时检测G#4,G#6,G#7吗?尝试使用这个伪正则表达式“/…(G#”)([0-9]+)?…/”或者如果您不希望不存在和弦,您可以手动放置所有变体“/…(G#”)(4 | 6 | 7…| 11 |…/”在TranssenoteCallback中,您将在$match[1]G中,然后您必须检查count($match)==2,如果条件为真,您可以从$match[2]中选择数字我终于得到了我需要的东西。谢谢我想检测它是a#键还是b键,而不是音符检测。