代码之家  ›  专栏  ›  技术社区  ›  MultiDev

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

  •  0
  • MultiDev  · 技术社区  · 12 年前

    我正试着把字符串中的最后一个元音去掉。例如:

    $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 回复  |  直到 12 年前
        1
  •  2
  •   Daniel Aranda    12 年前

    使用正则表达式,我们可以做到:

    $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]*)查找任何非元音
        2
  •  0
  •   sanath_p    12 年前

    希望这能奏效

    $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;
    
    推荐文章