Ví dụ
<?php
$my_string = "Hi there, this is a sample ";
$len = mb_strlen($my_string);
print_r("The number of characters in the string is ");
echo $len;
?>
Kết quả
The number of characters in the string is 27
Giải thích
Chuỗi được định nghĩa (có dấu cách thừa ở cuối):
$my_string = "Hi there, this is a sample ";
Độ dài chuỗi tính bằng mb_strlen() (hỗ trợ multi-byte/UTF-8). Kết quả gán cho biến, in ra màn hình:
$len = mb_strlen($my_string);
print_r("The number of characters in the string is ");
echo $len;
Lưu ý: strlen() đếm byte, mb_strlen() đếm ký tự (dùng cho UTF-8). Ví dụ có ký tự tiếng Việt cần dùng mb_strlen.