好的,所以您需要处理一些事情。
首先,您希望能够在数组中循环。这很简单:使用模数运算符,在 php 中是%
.
function transpose($chord, $increment) {
$map = array('A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#');
// Get the index of the given chord
$index = array_search($chord, $map);
if($index === false)
return false;
// Get the transposed index and chord
$transpose_index = ($index + $increment) % count($map);
if($transpose_index < 0)
$transpose_index += count($map);
return $map[$transpose_index];
}
其次,您希望能够去除对您而言重要的实际和弦。您可以使用正则表达式 (RegEx)执行此操作:
function transposeFull($chords, $increment) {
// This RegEx looks for one character (optionally followed by a sharp).
// .\#?
// This RegEx looks for an optional series of characters which are not /
// [^\/]*
// Put them together to get a RegEx that looks for an expanded chord
// (.\#?)([^\/]*)
// Then, do it again, but add a / first, and make it optional.
// (\/(.\#?)([^\/]*))?
$regex = '%(.\#?)([^\/]*)(\/(.\#?)([^\/]*))?%';
// Note that the () allow us to pull out the matches.
// $matches[0] is always the full thing.
// $matches[i] is the ith match
// (so $matches[3] is the whole optional second chord; which is not useful)
$matches = array();
preg_match($regex, $chords, $matches);
// Then, we get any parts that were matched and transpose them.
$chord1 = (count($matches) >= 2) ? transpose($matches[1], $increment) : false;
$expanded1 = (count($matches) >= 2) ? $matches[2] : '';
$chord2 = (count($matches) >= 5) ? transpose($matches[4], $increment) : false;
$expanded2 = (count($matches) >= 6) ? $matches[5] : '';
// Finally, put it back together.
$chords = '';
if($chord1 !== false)
$chords .= $chord1.$expanded1;
if($chord2 !== false)
$chords .= '/'.$chord2.$expanded2;
return $chords;
}