문자열에서 마지막 단어의 길이를 찾으려면 PHP 코드는 다음과 같습니다. -
예시
<?php
function last_word_len($my_string){
$position = strrpos($my_string, ' ');
if(!$position){
$position = 0;
} else {
$position = $position + 1;
}
$last_word = substr($my_string,$position);
return strlen($last_word);
}
print_r("The length of the last word is ");
print_r(last_word_len('Hey')."\n");
print_r("The length of the last word is ");
print_r(last_word_len('this is a sample')."\n");
?> 출력
The length of the last word is 3 The length of the last word is 6
문자열을 매개변수로 사용하는 'last_word_len'이라는 PHP 함수가 정의되어 있습니다. -
function last_word_len($my_string)
{
//
} 'strrpos' 함수를 사용하여 다른 문자열 내부의 첫 번째 공백을 찾습니다. 해당 위치가 있으면 0으로 할당되고 그렇지 않으면 1 −
증가합니다.$position = strrpos($my_string, ' ');
if(!$position){
$position = 0;
} else{
$position = $position + 1;
} 위치를 기준으로 문자열의 하위 문자열을 찾고 이 문자열의 길이를 찾아서 출력으로 반환합니다. 이 함수 외부에서 두 개의 다른 샘플에 대해 매개변수를 전달하여 함수가 호출되고 출력이 화면에 인쇄됩니다.