2009-08-13 15 views
2

I完全に私は正規表現の専門家ではないですとしてこれを行う方法は考えている。..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()です。

関連する問題