我正在使用substr_count來統計一個單詞的使用次數。 但它沒有返回我想要的結果。 這裏是我的示例代碼:substr count返回錯誤結果
<?php
echo substr_count("The Hello world. Therefore the world is nice","the");
?>
這將返回這3串數字3。我希望它只返回2.因爲有2個。第三個是這個詞的一部分,所以它不是一個。 我想到了正則表達式,但我並不擅長這些。有什麼建議麼 ?
我正在使用substr_count來統計一個單詞的使用次數。 但它沒有返回我想要的結果。 這裏是我的示例代碼:substr count返回錯誤結果
<?php
echo substr_count("The Hello world. Therefore the world is nice","the");
?>
這將返回這3串數字3。我希望它只返回2.因爲有2個。第三個是這個詞的一部分,所以它不是一個。 我想到了正則表達式,但我並不擅長這些。有什麼建議麼 ?
我認爲substr_count的用法是不同的。 語法:
int substr_count (string $haystack , string $needle [, int $offset = 0 [, int $length ]])
substr_count()返回在草堆串發生針子的次數。請注意,針是區分大小寫的。
有3「的其中有一個空間的the
。 將因此而
試試這個:
<?php
echo substr_count("The Hello world. Therefore the world is nice","the ");
?>
如果它的標點符號後面呢?像。那麼它不會計算它,但應該算它,因爲它仍然是同一個詞。 – cppit
這裏是計數串出現的另一種方式,
<?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;
它沒有工作......它返回錯誤的計數 – cppit
No.Bro它的一個工作代碼。唯一要記住的是它會發現'the'而不是'The'的發生。 –
您好@fogsy我已經更新了我的答案。請檢查一下。它現在正在爲'the'和'The'工作。 –
<?php
echo preg_match_all('/\bthe\b/i', 'The Hello World. Therefore the world is nice', $m);
?>
第一個參數是模式,其中\b
表示單詞邊界,/i
修飾符表示情況下敏感。
第二個參數是匹配的主題。
第三個參數填充了匹配數組。我的舊PHP需要它,5.4以後的版本不需要它。
任何其他方式來實現我需要的結果?我正在考慮正則表達式,你對此熟悉嗎? – cppit
@fogsy還有另外一種方法..請檢查我的第二個答案 –