View Full Version : How to replace non-vowels in a string?

08-08-2008, 11:11 PM
I am trying to extract vowels from a string. One thing is to replace anything that is not a,e,i,o,u with "".

$fname_out = "test";

$vowels = array ('a', 'e', 'i', 'o', 'u');

One option (does not work) I considered:

$vow_fname = preg_replace(array('/^[^$vowels]+$/'), '', $fname_out);

The other (does not work):

$vow_fname = preg_replace('/^[^aeiou]+$/', '', $fname_out);

And another (does not work):

$vow_fname = str_replace(!($vowels), "", $fname_out);

Could you please suggest the right solution. I have been scouring php.net and other sites, but cannot seem to get the solution :(

Thank you! :)


08-08-2008, 11:21 PM
Re-read it. Will do another example in a min

08-08-2008, 11:27 PM
Wouldn't this work for what you're trying to accomplish?

$vow_fname = str_replace($vowels," ",$fname_out);

All of the vowels should be spaces in $vow_fname.

08-08-2008, 11:28 PM
close with your second preg_replace one, but you don't want to restrict it as much as you have. Your regular expression is saying 'replace one or more successive consonants betweent the start and end of the string', which isn't what you want.

$result = preg_replace('/[^aeiou]/i','',$source);

should do what you want.

08-08-2008, 11:41 PM
GJay, it works a treat!

Thanks a billion!



08-08-2008, 11:45 PM
I found this, doesn't delete punctuation.

$string ="this is a test which should delete all consonants, yes?";
$string = preg_replace('/(?:[bcdfghjklmnpqrstvwxyz]|(?<=[aeiou]))/','', $string);
echo $string;

Probably OTT and could probably be done easily in gjay's code somehow.