MultiDev
MultiDev

Reputation: 10649

PHP: Find last occurrence in string

I am trying to drop the last vowel in a string. For example:

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

How can I do this?

Thanks

Upvotes: 0

Views: 409

Answers (2)

Daniel Aranda
Daniel Aranda

Reputation: 6552

With a regular expression we could do it:

$str = 'This is a string of words.';
echo preg_replace('/([aeiou]{1})([^aeiou]*)$/i', '$2', $str);
//output: This is a string of wrds.

Explaining a bit more the regular expression:

  • $ <- the end of the phrase
  • ([aeiou]{1}) <- looks for one vowel
  • ([^aeiou]*) looks for any that is not a vowel

Upvotes: 2

sanath_p
sanath_p

Reputation: 2218

Hope this works

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

Upvotes: 0

Related Questions