如何检测和回声单词中的最后一个元音? [英] How to detect and echo the last vowel in a word?

查看:108
本文介绍了如何检测和回声单词中的最后一个元音?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$word = "Acrobat" (or Apple, Tea etc.)

如何用php检测并回显给定单词的最后一个元音?我尝试了preg_match函数,用了Google几个小时,但找不到合适的解决方案.

How can I detect and echo the last vowel of a given word with php? I tried preg_match function, google'd for hours but couldn't find a proper solution.

字符串中可以包含诸如ü,ö的多字节字母.

There can be multibyte letters like ü, ö in the string.

推荐答案

这是捕获字符串中最后一个元音的多字节安全版本.

Here's a multibyte safe version of catching the last vowel in a string.

$arr = array(
    'Apple','Tea','Strng','queue',
    'asartä','nő','ağır','NOËL','gør','æsc'
);

/*  these are the ones I found in character viewer
    in Mac so these vowels can be extended. don't
    forget to add both lower and upper case versions
    of new ones because personally I wouldn't rely
    on the i (case insensitive) flag in the pattern
    for multibyte characters.
*/
$vowels =
    'aàáâãāăȧäảåǎȁąạḁẚầấẫẩằắẵẳǡǟǻậặæǽǣ' .
    'AÀÁÂÃĀĂȦÄẢÅǍȀȂĄẠḀẦẤẪẨẰẮẴẲǠǞǺẬẶÆǼǢ' .
    'EÈÉÊẼĒĔĖËẺĚȄȆẸȨĘḘḚỀẾỄỂḔḖỆḜ' .
    'eèéêẽēĕėëẻěȅȇẹȩęḙḛềếễểḕḗệḝ' .
    'IÌÍÎĨĪĬİÏỈǏỊĮȈȊḬḮ' .
    'iìíîĩīĭıïỉǐịįȉȋḭḯ' .
    'OÒÓÔÕŌŎȮÖỎŐǑȌȎƠǪỌØỒỐỖỔȰȪȬṌṐṒỜỚỠỞỢǬỘǾŒ' .
    'oòóôõōŏȯöỏőǒȍȏơǫọøồốỗổȱȫȭṍṏṑṓờớỡởợǭộǿœ' .
    'UÙÚÛŨŪŬÜỦŮŰǓȔȖƯỤṲŲṶṴṸṺǛǗǕǙỪỨỮỬỰ' .
    'uùúûũūŭüủůűǔȕȗưụṳųṷṵṹṻǖǜǘǖǚừứữửự'
;

// set necessary encodings
mb_internal_encoding('UTF-8');
mb_regex_encoding('UTF-8');

// and loop
foreach ($arr as $word) {

    $vow = mb_ereg_replace('[^'.$vowels.']','',$word);
    // get rid of all consonants (non-vowels in this pattern)
    $lastVw = mb_substr($vow,-1);
    // and get the last one from the remaining vowels

    if (empty($lastVw))
    // it evaluates this line when there's no vowel in the string
        echo "there's no vowel in <b>\"$word\"</b>." . PHP_EOL;
    else
    // and vice versa
        echo "last vowel in <b>\"$word\"</b> is " .
        "<span style=\"color:#F00\">{$lastVw}</span>" . PHP_EOL;    
}

这是输出.

苹果" 中的最后一个元音是 e
茶" 中的最后一个元音是 a
"Strng" 中没有元音.
队列" 中的最后一个元音是 e
asartä" 中的最后一个元音是 ä
nő" 中的最后一个元音是 ő
ağır" 中的最后一个元音是 ı
NOËL" 中的最后一个元音是 Ë
gør" 中的最后一个元音是 ø
æsc" 中的最后一个元音是 æ

last vowel in "Apple" is e
last vowel in "Tea" is a
there's no vowel in "Strng".
last vowel in "queue" is e
last vowel in "asartä" is ä
last vowel in "nő" is ő
last vowel in "ağır" is ı
last vowel in "NOËL" is Ë
last vowel in "gør" is ø
last vowel in "æsc" is æ

这篇关于如何检测和回声单词中的最后一个元音?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆