php
PHP - str_word_count 함수
mixed str_word_count ( string $string [, int $format [, string $charlist ]] )
(PHP 4 >= 4.3.0, PHP 5)
format 인자는 선택적인 정수를 대입하는데, string 안의 단어 수를 셉니다. format 를 지정하면, 반환 값은 배열로써, 다음 표의 값에 따라 결정됩니다.
charlist 인자는 '단어'로 간주할 추가 문자 목록이며, PHP 5.1 부터 사용 가능합니다.
(PHP 4 >= 4.3.0, PHP 5)
format 인자는 선택적인 정수를 대입하는데, string 안의 단어 수를 셉니다. format 를 지정하면, 반환 값은 배열로써, 다음 표의 값에 따라 결정됩니다.
0 | 발견한 단어 수를 반환합니다. |
1 | string 안에서 발견한 모든 단어를 배열로 반환합니다. |
2 | 키는 string 안에서 단어의 위치이고, 값은 단어입니다. |
charlist 인자는 '단어'로 간주할 추가 문자 목록이며, PHP 5.1 부터 사용 가능합니다.
<?php
$str = "Hello fri3nd, you're
looking good today!";
// string 안에서 발견한 모든 단어를 가진 배열을 반환합니다.
print_r(str_word_count($str, 1));
/*
결과:
Array
(
[0] => Hello
[1] => fri
[2] => nd
[3] => you're
[4] => looking
[5] => good
[6] => today
)
*/
// 키는 string 안에서 단어의 위치이고, 값은 단어인 배열을 반환합니다.
print_r(str_word_count($str, 2));
/*
결과:
Array
(
[0] => Hello
[6] => fri
[10] => nd
[14] => you're
[29] => looking
[46] => good
[51] => today
)
*/
print_r(str_word_count($str, 1, 'aaac3'));
/*
결과:
Array
(
[0] => Hello
[1] => fri3nd
[2] => you're
[3] => looking
[4] => good
[5] => today
)
*/
// format 을 지정하지 않으면 기본 0을 대입하게 됩니다.
echo str_word_count($str); // 결과: 7
?>
<?php
function count_words($string){
$string = trim(preg_replace("/\s+/"," ",$string));
$word_array = explode(" ", $string);
$num = count($word_array);
return $num;
}
$str = "Hello fri3nd, you're looking good today!";
echo count_words($str);
?>
0 댓글