2013-02-27 29 views
1

我正在寻找一种方式来找到另一句话句子出现在另一个句子的数量(在PHP)

例如(我有)句出现的次数:

你好兄弟,我一直在等待告诉你一些非常重要的东西。再见哥哥,我会看到你下周

,我正在寻找:

哥哥,我

这应该送给我的结果:

结果= 2

+0

[你尝试过什么?](HTTP:// WWW .whathaveyoutried.com /)请参阅[请教](http://stackoverflow.com/questions/ask-advice)。 – 2013-02-27 19:17:25

+2

所有你需要的是'substr_count' – Baba 2013-02-27 19:31:15

回答

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 
+0

,这使得基本情况下,如果字符串中没有文本,然后零发生的字符串被搜索(它不能是负面的权利) – Smita 2013-02-27 19:29:34

+0

谢谢Smita,正是我所需要的 – dinbrca 2013-02-27 20:22:26

+0

什么是使用数组的感觉和爆炸,如果你只有一个准备好的功能呢? – Hast 2013-02-27 22:53:07

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