在PHP字符串中正确形式的不定冠词(a,an)

Leo*_*Leo 6 php string cakephp

是否有一种简单的方法来替换字符串中的/ a以符合以下单词 - 与'S'在日期格式中的工作方式非常相似?

例如

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

--> This is an apple, this is a pear
Run Code Online (Sandbox Code Playgroud)

Luk*_*ers 7

看看这个,它通过了我自己的测试,看起来很稳固.

https://github.com/Kaivosukeltaja/php-indefinite-article


Tot*_*oto 6

试试这个 :

$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";
}
Run Code Online (Sandbox Code Playgroud)

输出:

an apple is a fruit
a banana is also a fruit
Run Code Online (Sandbox Code Playgroud)

  • 一所大学花了一个小时研究一个SO答案,发现它有问题...... (4认同)

dan*_*ood 6

您可以使用正则表达式来交换a /,具体取决于它后面的内容.更棘手的部分实际上将定义所有要交换的案例 - 它比'如果它后跟元音'更复杂.

何时使用/ an:

使用以辅音声音开头的之前的单词/缩写; 使用以元音开头的单词/缩写词.这是基于发音而不是拼写.

因此:

  • 一所大学
  • 一小时
  • 镱分子
  • 一只黄狗
  • 一个M.

开始使用正则表达式来解决它

$text = preg_replace("/(?=a|e|i|o|u|yt)a/", "an", $text);
Run Code Online (Sandbox Code Playgroud)

  • 呸,我的观点是语言,而不是使用的正则表达式/函数,这非常简单.根据"a"后跟元音进行基本交换不是不定冠词的正确形式. (3认同)