2

我正在寻找一种方法来查找另一个句子中的句子出现次数

例如(我有):

Do you have a different language or operating system? JavaScript is currently disabled in your browser and is required to

我正在寻找:

一个

这应该向我展示以下结果:

结果 = 1

因为如果你把 a 当作一个单词而不是一个 char 你会得到 1 作为结果:

“您有不同的语言或操作系统吗?JavaScript 目前在您的浏览器中被禁用,并且是必需的”Din。

4

3 回答 3

1

确实使用substr_count.

为了确保只匹配单词:在使用之前在单词前后添加一个空格,并使用.substr_count显式检查字符串开头或结尾处的单词substr

于 2013-03-03T21:34:39.517 回答
1

至于快速/简单地计算单词“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;  
于 2013-03-03T21:38:27.337 回答
0

不是最有效的解决方案,但似乎可以满足您的需求。

$search = 'a';
$str = "Do you have a different language or operating system? JavaScript is currently disabled in your browser and is required to";
$count = array_sum(array_map(function($val) use ($search) {if ($val == $search) { return 1; } else { return 0; }}, str_word_count($str, 1)));
于 2013-03-03T21:41:40.177 回答