另一句话中出现的句子数(以PHP表示)

时间:2013-02-27 19:16:51

标签: php

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

例如(我有):

  

你好兄弟,我一直在等你告诉你一件事   重要。再见的兄弟,下周我会见到你

我正在寻找:

  兄弟,我

这应该是我的结果:

  

result = 2

2 个答案:

答案 0 :(得分:2)

使用substr_count()功能

$str = "Hello brother, I have been waiting to tell you something very important. Good bye brother, I will see you next week";

echo substr_count($str, 'brother, I'); // 2

如果您需要不区分大小写的方法,只需将两个字符串设为小写或大写:

echo substr_count(strtolower($str), strtolower('brother, I')); // 2

答案 1 :(得分:1)

$str = "Hello brother, I have been waiting to tell you something very important. Good bye brother, I will see you next week"

// explode the string using delimiter 'brother, I', the no of occurance of 'brother, I' will be one less than than the number of element in resultant array.
eg

$resArr = explode("brother, I","$str");

$ans = count($resArr) -1

//assuming your input string is not starting or ending with delimiter ie 'brother, I' in this case