我正在尝试将最后一个元音放入一个字符串中。例如:
$string = 'This is a string of words.';
$vowels = array('a','e','i','o','u');
if (in_array($string, $vowels)) {
// $newstring = '' // Drop last vowel.
}
echo $newstring; // Should echo 'This is a string of wrds.';
我该怎么做?
由于
答案 0 :(得分:2)
使用正则表达式我们可以做到:
$str = 'This is a string of words.';
echo preg_replace('/([aeiou]{1})([^aeiou]*)$/i', '$2', $str);
//output: This is a string of wrds.
解释一下正则表达式:
答案 1 :(得分:0)
希望这有效
$string = 'This is a string of words.';
$words = explode(" ", $string);
$lastword = array_pop($words);
$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U", " ");
$newlastword = str_replace($vowels, "", $lastword);
$newstring='';
foreach ($words as $value) {
$newstring=$newstring.' '.$value;
}
$newstring=$newstring.' '.$newlastword;
echo $newstring;