找出一个单词出现的次数

时间:2010-02-10 11:33:02

标签: php string search

dogdogdogdogsdogdogdogs

如果没有正则表达式,我怎么算“狗”和“狗”出现多少次?

5 个答案:

答案 0 :(得分:11)

使用substr_count()

  

substr_count()返回在haystack字符串中出现针子串的次数。请注意针头区分大小写。

,您说您想要计算dog dogs的出现次数。如果先检查dogs,然后检查dog,则会得到偏差的结果(因为dogs会被计算两次)。

如果您的示例字面上为dogdogs,则需要从dogs中减去dog的计数,以获得正确的计数。

如果您正在使用不同单词的程序化方法,则需要事先检查是否有任何单词是另一个单词的一部分。

为更简单的方法欢呼为SilentGhost。

答案 1 :(得分:3)

使用substr_count()

substr_count('dogdogdogdog', 'dog');

答案 2 :(得分:1)

substr_count函数应该只是你所要求的:

$str = 'dogdogdogdogsdogdogdogs';
$a = substr_count($str, 'dog');
var_dump($a);

会得到你:

int 7


引用其文档页面:

int substr_count  ( string $haystack  , string $needle  
    [, int $offset = 0  [, int $length  ]] )
  

substr_count()返回的数字   针子串发生的次数   干草堆串。请注意   针是区分大小写的。

答案 3 :(得分:0)

substr_count

substr_count('dogdogdogdogsdogdogdogs', 'dog');
// returns 7

答案 4 :(得分:0)

好吧,除了substr_count()之外,您还可以使用优质的str_replace()

$string = 'dogdogdogdogsdogdogdogs';

$str = str_replace('dogs', '', $string, $count);
echo 'Found ' . $count . ' time(s) "dogs" in ' . $string;

$str = str_replace('dog', '', $str, $count);
echo 'Found ' . $count . ' time(s) "dog" in ' . $string;

这种方法解决了the problem Pekka mentioned in his answer。作为额外的好处,您还可以使用str_ireplace()进行不区分大小写的搜索,这是substr_count()无法使用的内容。

从PHP手册:

  

substr_count()返回的数字   次 needle 子串发生在    haystack 字符串。 请注意    needle 区分大小写。

相关问题