2012-11-02 116 views
1

我正在使用substr_count来统计一个单词的使用次数。 但它没有返回我想要的结果。 这里是我的示例代码:substr count返回错误结果

<?php 
    echo substr_count("The Hello world. Therefore the world is nice","the"); 
?> 

这将返回这3串数字3。我希望它只返回2.因为有2个。第三个是这个词的一部分,所以它不是一个。 我想到了正则表达式,但我并不擅长这些。有什么建议么 ?

回答

0

我认为substr_count的用法是不同的。 语法:

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

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

请参阅 http://php.net/manual/en/function.substr-count.php

+0

任何其他方式来实现我需要的结果?我正在考虑正则表达式,你对此熟悉吗? – cppit

+1

@fogsy还有另外一种方法..请检查我的第二个答案 –

2

您需要the后添加空间,它只能包括后

<?php 
     echo substr_count("The Hello world. Therefore the world is nice","the "); 
    ?> 
+1

如果标点符号后面跟着什么呢?像。那么它不会计算它,但应该算它,因为它仍然是同一个词。 – cppit

+0

你需要找出一种方法来解决像'str_replace'之前做计数 – Rab

0

有3“的其中有一个空间的the。 将因此而

试试这个:

<?php 
    echo substr_count("The Hello world. Therefore the world is nice","the "); 
?> 
+0

如果它的标点符号后面呢?像。那么它不会计算它,但应该算它,因为它仍然是同一个词。 – cppit

1

这里是计数串出现的另一种方式,

<?php 
$string = "The Hello world. Therefore the world is nice"; 
$substring = 'the'; 

$cArr = explode($substring,strtolower($string)); 
echo $substring_count = count($cArr) - 1; 
?> 

OR

$wordCounts = array_count_values(str_word_count(strtolower($string),1)); 
echo $theCount = (isset($wordCounts['the'])) ? $wordCounts['the'] : 0; 
+0

它没有工作......它返回错误的计数 – cppit

+0

No.Bro它的一个工作代码。唯一要记住的是它会发现'the'而不是'The'的发生。 –

+0

您好@fogsy我已经更新了我的答案。请检查一下。它现在正在为'the'和'The'工作。 –

0
<?php 
    echo preg_match_all('/\bthe\b/i', 'The Hello World. Therefore the world is nice', $m); 
?> 

第一个参数是模式,其中\b表示单词边界,/i修饰符表示情况下敏感。

第二个参数是匹配的主题。

第三个参数填充了匹配数组。我的旧PHP需要它,5.4以后的版本不需要它。