Jump to content

preg_replace: convert a to an, based if next letter is vowel.


Hybride

Recommended Posts

Hey everyone, I've been trying to use preg_replace to, as the topic states, convert the word "a" to "an" depending if the letter after it is either a vowel or a consonant. I have several versions  of code that does either but not both.

 

$testwith = "A orange piece of a paper sheet, a eastern East of a paper sheet.";
echo ucfirst(preg_replace("/[Aa][[:space:]]/", "an ", $testwith)); 
echo ucfirst(preg_replace("/^[Aa][[:space:]]/", "an ", $testwith)); 
echo ucfirst(preg_replace("/[Aa][[:space:]]+[aeiouAEIOU]/", "an ", $testwith));

These are the outputs:

1. "An orange piece of an paper sheet, an eastern East of an paper sheet.", so all a's to an's.
2. "An orange piece of a paper sheet, a eastern East of a paper sheet.", so replaces first word only.
3. "An range piece of a paper sheet, an astern East of an paper sheet.", so it replaces the proper a to an, but also removes the vowel.

 

I tried doing this also:

if (preg_match("/([Aa][[:space:]])+[aeiouAEIOU]/",$testwith)) {//first check if there is a match of a + vowel
echo ucfirst(preg_replace("/[Aa][[:space:]]/", "an ", $testwith));//then replace the a to an
}

but that also converted all the a's to an's.

 

Is there some way to do this without replacing the vowel; or, if necessary, split up the query? I know it's a simple thing am missing. Thanks for your help!

$testwith = "A orange piece of a paper sheet, a eastern East of a paper sheet.";
$testwith = preg_replace('#\b(a)\b(?:\s(a|e|i|o|u))#i' , '$1n $2', $testwith);
echo $testwith;

 

Outputs:

An orange piece of a paper sheet, an eastern East of a paper sheet.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.