views:

65

answers:

3

Is there an easy way to substitute a/an in a string to agree with the following word - much the same as the way 'S' works in Date format?

e.g.

$apple = 'apple';
$pear = 'pear';
echo "This is a $apple, this is a $pear."

--> This is an apple, this is a pear
+2  A: 

not sure if it works in PHP that way but a really simple solution would be:

$string = preg_replace('/\ba\b\s([aeiou])/',   'an $1', $string);
$string = preg_replace('/\ban\b\s([^aeiou])/', 'an $1', $string);

(Not sure about the a/an rule as there is no such rule in german and i usually use the one that sounds better)

Explanation:

\b is a word boundary, so \ba\b looks for the word a, followed by a space and one of the letters [aeiou]. The letter is captured to $1 and the expression is replaced with an followed by the captured letter.

dbemerlin
Thanks - equal first place with M42.
Leo
+5  A: 

Try this :

$l = array('a apple is a fruit', 'a banana is also a fruit');

foreach($l as $s) {
  $s = preg_replace('/(^| )a ([aeiouAEIOU])/', '$1an $2', $s);
  echo $s,"\n";
}

output:

an apple is a fruit
a banana is also a fruit
M42
needed to use [aeiouAEIOU] as it is for a title where the significant words are capitalised. Thanks.
Leo
Right, i added the uppercase letters.
M42
+4  A: 

You could use a regular expression to swap the a/and depending on what follows it. The trickier part will actually be defining all of the cases on which to swap - it is more complicated then 'if its followed by a vowel'.

When to use a/an:

Use a before words/abbreviations that begin with a consonant sound; use an before words/abbreviations that begin with a vowel sound. This is based on pronunciation, not spelling.

Hence:

  • a university
  • an hour
  • an ytterbium molecule
  • a yellow dog
  • a U
  • an M

Beginning of a regex to solve it

$text = preg_replace("/(?=a|e|i|o|u|yt)a/", "an", $text);
danielgwood
the regex is wrong. it asserts beginning in the position of an a.
sreservoir
Bah, my point was the language rather than the regex/function used, which is pretty simple. Doing a basic swap according to whether 'a' is followed by a vowel just isn't the correct form of an indefinite article.
danielgwood
You've made some interesting points. Common usage is the key to this. An hotel is correct, but actual usage and pronunciation depends on where in the country (England) you come from, amongst other things. Therefore a hotel is equally correct. Making other distinctions, e.g. a university, an umbrella is not easily done algorithmically.
Leo