Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Chương trình PHP tìm độ dài từ cuối cùng trong chuỗi

Ví dụ

<?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");
?>

Kết quả

The length of the last word is 3
The length of the last word is 6

Giải thích

Hàm last_word_len nhận chuỗi làm tham số:

function last_word_len($my_string) { // }

Tìm vị trí dấu cách cuối cùng bằng strrpos(). Nếu không có (chuỗi 1 từ), position = 0. Ngược lại tăng 1 để bỏ qua dấu cách:

$position = strrpos($my_string, ' ');
if (!$position) { $position = 0; }
else { $position = $position + 1; }

Lấy substring từ vị trí đó, trả về độ dài chuỗi con đó. Gọi hàm với 2 mẫu khác nhau in kết quả.

Lưu ý: Cách này không xử lý tốt chuỗi có nhiều dấu cách liên tiếp hoặc dấu cách ở cuối. Cách tốt hơn: strlen(trim(strrchr($str, ' '))) hoặc explode(' ', trim($str)) lấy phần tử cuối.