PHP:在字符串中查找最后一次出现

时间:2014-07-21 19:40:57

标签: php html string str-replace

我正在尝试将最后一个元音放入一个字符串中。例如:

$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.';

我该怎么做?

由于

2 个答案:

答案 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.

解释一下正则表达式:

  • $< - 短语的结尾
  • ([aeiou] {1})< - 寻找一个元音
  • ([^ aeiou] *)寻找任何不是元音的文件

答案 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;