ตัวอย่างโค้ด
<?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);
}
echo "The length of the last word is " . last_word_len('Hey') . "\n";
echo "The length of the last word is " . last_word_len('this is a sample') . "\n";
?>
ผลลัพธ์
The length of the last word is 3
The length of the last word is 6
คำอธิบาย
strrpos() หาตำแหน่ง Space สุดท้าย (Last Occurrence)
- ถ้าไม่มี Space (Single Word) → Position = 0
- ถ้ามี Space → Position = Last Space + 1 (เริ่มคำสุดท้าย)
substr() ตัดคำสุดท้ายออกมา
strlen() วัดความยาว
Edge Cases
<?php
// Trailing spaces
echo last_word_len("hello world "); // 0 (last word is empty)
// Solution: trim first
function last_word_len_fixed($str) {
$str = rtrim($str);
$pos = strrpos($str, ' ');
$pos = ($pos === false) ? 0 : $pos + 1;
return strlen(substr($str, $pos));
}
echo last_word_len_fixed("hello world "); // 5
?>
วิธี Alternative (Regex)
<?php
function last_word_len_regex($str) {
preg_match('/(\S+)\s*$/', $str, $matches);
return $matches ? strlen($matches[1]) : 0;
}
?>