Ollie's algorithm was a nice start, but it didn't apply the marks correctly. For example, qiao1 became qīāō. This one is correct and complete. You can easily see how the replacement rules are defined.
It does the whole thing for tone 5 as well, although it doesn't affect the output, except for deleting the number. I left it in, in case you want to do something with tone 5.
The algorithm works as follows:
- The word and tone are provided in $match[1] and [2]
- A star is added behind the letter that should get the accent mark
- A letter with a star is replaced by that letter with the correct tone mark.
Example:
qiao => (iao becomes ia*o) => qia*o => qiǎo
This strategy, and the use of strtr
(which prioritizes longer replacements), makes sure that this won't happen:
qiao1 => qīāō
function pinyin_addaccents($string) {
# Find words with a number behind them, and replace with callback fn.
return preg_replace_callback(
'~([a-zA-Züü]+)(d)~',
'pinyin_addaccents_cb',
$string);
}
# Helper callback
function pinyin_addaccents_cb($match) {
static $accentmap = null;
if( $accentmap === null ) {
# Where to place the accent marks
$stars =
'a* e* i* o* u* ü* '.
'A* E* I* O* U* ü* '.
'a*i a*o e*i ia* ia*o ie* io* iu* '.
'A*I A*O E*I IA* IA*O IE* IO* IU* '.
'o*u ua* ua*i ue* ui* uo* üe* '.
'O*U UA* UA*I UE* UI* UO* üE*';
$nostars = str_replace('*', '', $stars);
# Build an array like Array('a' => 'a*') and store statically
$accentmap = array_combine(explode(' ',$nostars), explode(' ', $stars));
unset($stars, $nostars);
}
static $vowels =
Array('a*','e*','i*','o*','u*','ü*','A*','E*','I*','O*','U*','ü*');
static $pinyin = Array(
1 => Array('ā','ē','ī','ō','ū','ǖ','ā','ē','ī','ō','ū','ǖ'),
2 => Array('á','é','í','ó','ú','ǘ','á','é','í','ó','ú','ǘ'),
3 => Array('ǎ','ě','ǐ','ǒ','ǔ','ǚ','ǎ','ě','ǐ','ǒ','ǔ','ǚ'),
4 => Array('à','è','ì','ò','ù','ǜ','à','è','ì','ò','ù','ǜ'),
5 => Array('a','e','i','o','u','ü','A','E','I','O','U','ü')
);
list(,$word,$tone) = $match;
# Add star to vowelcluster
$word = strtr($word, $accentmap);
# Replace starred letter with accented
$word = str_replace($vowels, $pinyin[$tone], $word);
return $word;
}