在句子中出现句子/单词/字符 - 只计算单词(如果可能,不计算正则表达式)(PHP)

时间:2013-03-03 21:28:57

标签: php sentence

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

例如(我有):

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

我正在寻找:

  

这应该是我的结果:

  

result = 1

因为如果你把一个单词算作一个单词而不是一个单词,那么结果会得到1:

“您是否有 不同的语言或操作系统?您的浏览器目前禁用了JavaScript,并且需要” 嚣。

3 个答案:

答案 0 :(得分:1)

确实使用substr_count

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

答案 1 :(得分:1)

至于计算WORD“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;  

答案 2 :(得分: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)));