2009-08-13 2 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()는 정규 표현식에 일치하는 수를 반환 - 당신의 예를 다시 작성 : - preg_match_all 간단한 문자열 검색을위한 비트 잔인한 -하지만

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

을 더 유용 할 수 있습니다 당신은 문자열에서 숫자의 수를 계산하기를 원한다면 말 : 단순한 문자열에 대한

$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() 두 인수가 먼저 나옵니다.

관련 문제