0

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

1
  • A generic answer to the question in your title is the use of strrpos Commented Jul 21, 2014 at 19:48

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

can you explain the regular expression ? .Will be helpful for many .I am the guy who posted 8 line answer to this question . :p
Yes, thank you for your answer, it seems to work, but could you please explain the expression?
Adding explanation in the answer @JohnRobinson
you can safely remove (.*) and $1 from regex and replacement string resp.
0

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;

8 Comments

$string = 'This is a string of words with multiple vowels.';
+ doesn't do what you think it does
$newlastword is not used
It won't work if the last word doesn't contain any wovel btw.
now it works .@malet it works because nothing will be replaced
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.