Ví dụ
<?php $my_string = 'Hi there, this is a sample statement'; echo "The first word of the string is " . strtok($my_string, " "); ?>
Kết quả
The first word of the string is Hi
Giải thích
Chuỗi được định nghĩa:
$my_string = 'Hi there, this is a sample statement';
Hàm strtok() tách chuỗi thành các phần theo delimiter. Tách trước dấu cách đầu tiên, phần đầu tiên hiển thị làm output:
echo "The first word of the string is " . strtok($my_string, " ");
Lưu ý: strtok() dùng trạng thái nội bộ, gọi lại không cần chuỗi gốc. Cách khác: explode(' ', $str)[0] hoặc strstr($str, ' ', true) (PHP 5.3+).