2009-08-13 43 views
2

我完全不知道如何做到這一點,因爲我不是一個正則表達式的專家..PHP:如何搜索和計算一個字符串指定的文本?

但我想搜索和計算一個長字符串指定不區分大小寫的文本,例如:

的功能:

int count_string (string $string_to_search, string $input_search)

例如使用情況和效果:

$my_string = "Hello my name is John. I love my wife, child, and dog very much. My job is a policeman."; 

print count_string("my", $my_string); // prints "3" 
print count_string("is", $my_string); // prints "2"

是否有任何內置功能來做到這一點?

任何形式的幫助,將不勝感激:)

回答

9

substr_count()是你在找什麼。

substr_count(strtolower($ string),strtolower($ searchstring))會使計數不敏感。 (gnarf提供)

2

preg_match_all()返回一個正則表達式匹配數 - 重寫你的例子:

echo preg_match_all("/my/i", $my_string, $matches); 
echo preg_match_all("/is/i", $my_string, $matches); 

雖然 - preg_match_all是一個簡單的字符串搜索有點矯枉過正 - 這可能是更有益說,如果你想計算數字的字符串數量:

$my_string = "99 bottles of beer on the wall, 99 bottles of beer\n"; 
$my_stirng .= "Take 1 down pass it around, 98 bottles of beer on the wall\n"; 

// echos 4, and $matches[0] will contain array('99','99','1','98'); 
echo preg_match_all("/\d+/", $my_string, $matches); 

對於簡單的字符串使用substr_count()由邁克爾的建議 - 如果你想不區分大小寫只有strtolower()兩個論點第一。

相關問題