至于快速/简单地计算单词“a”在字符串中使用的次数:
$sent = "Do you have a different language or operating system? JavaScript is currently disabled in your browser and is required to";
if( preg_match( '/ a /', $sent, $matches ) ) { # a space before and after makes it a word not a letter.
echo count( $matches );
}
但这仍然不能告诉您在所有情况下肯定有多少个句子;要做到这一点需要一个非常复杂的正则表达式。
--> 编辑:
要在句子开头和其他任何地方添加单词“a”,您可以这样做:
$sent = "A different language or operating system? JavaScript is currently disabled in your browser and is required to eat a walrus";
$patterns = array( '/ a /', '/A /' );
$ctr = 0;
foreach( $patterns as $p ) {
if( preg_match( $p, $sent, $matches ) ) {
$ctr += count( $matches );
}
}
echo $ctr;