본문 바로가기

PHP/PHP7 예비학교

[PHP] 문자열이 포함되어 있는 개수 확인 - substr_count(), mb_substr_count()

substr_cunt()와 mb_substr_cunt()는 문자열에 포함되어 있는 개수를 확인하는 기능은 같습니다.

하지만 멀티바이트 문자 검색에는 반드시 mb_substr_cunt()를 사용해야합니다.

substr_count()


substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] ) : int
인자 설명
$haystack 검색 문자열
$needle 검색 문장
$offset 시작 위치
$length 시작 위치에서부터 길이
<?php
echo substr_count("zero one two one", "one");	//2
?>

 

$offset을 8로 지정한다면 "zero one two one"을 "two one"에서 "one"을 찾습니다.

<?php
echo substr_count("zero one two one", "one", 8);	//1
?>

 

$offset을 5로 $length를 6을 지정한다면 "zero one two one"을 "one two"에서 "one을 찾습니다.

<?php
echo substr_count("zero one two one", "one", 5, 6);	//1
?>

mb_substr_count()


mb_substr_count ( string $haystack , string $needle [, string $encoding = mb_internal_encoding() ] ) : int
인자 설명
$haystack 검색 문자열
$needle 검색 문장
$encoding 인코딩 방식
<?php
echo mb_substr_count("zero one two one", "one");	//2
echo mb_substr_count("영 일 이 일", "일");		//3
echo mb_substr_count("영 일 이 일", "일", "UTF-8");	//2
?>

영문자는 상관이 없지만 한글은 인코딩 방식을 설정해주지 않으면 올바른 값을 반환하지 않습니다.

반응형