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!

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.