หากต้องการค้นหาความยาวของคำสุดท้ายในสตริง โค้ด 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
มีการกำหนดฟังก์ชัน PHP ชื่อ 'last_word_len' ซึ่งรับสตริงเป็นพารามิเตอร์ -
function last_word_len($my_string)
{
//
} พบการเกิดขึ้นครั้งแรกของช่องว่างภายในสตริงอื่นโดยใช้ฟังก์ชัน 'strrpos' หากมีตำแหน่งนั้นอยู่ จะถูกกำหนดให้เป็น 0 มิฉะนั้น จะเพิ่มขึ้น 1 −
$position = strrpos($my_string, ' ');
if(!$position){
$position = 0;
} else{
$position = $position + 1;
} พบสตริงย่อยของสตริงตามตำแหน่ง และพบความยาวของสตริงนี้และส่งกลับเป็นเอาต์พุต นอกฟังก์ชันนี้ ฟังก์ชันนี้เรียกโดยการส่งผ่านพารามิเตอร์สำหรับตัวอย่างสองตัวอย่างที่แตกต่างกันและเอาต์พุตจะถูกพิมพ์บนหน้าจอ