Current Location: Home> Latest Articles> PHP strtok() Function Tutorial and Example Explanation

PHP strtok() Function Tutorial and Example Explanation

gitbox 2025-06-30

Introduction

PHP is a widely used server-side scripting language for web development. In this article, we will explore the PHP strtok() function, which splits a string into multiple tokens based on a specified delimiter and returns the first token. We will provide detailed examples and help you understand its usage.

Function Syntax

strtok(string $str, string $delimiter): string|false

Parameters

  • $str: The string to be split.
  • $delimiter: The delimiter, which can be a single character or a string.

Return Value

If a token is found, strtok() returns the token; otherwise, it returns false if no token is found.

Example Code

Let's walk through some examples to demonstrate how to use the strtok() function.

Example 1: Basic String Splitting


$str = "Hello World! Welcome to PHP.";
$delimiter = " ";
$token = strtok($str, $delimiter);
while ($token !== false) {
    echo $token . "<br>";
    $token = strtok($delimiter);
}

This code will output the following:

Hello

World!

Welcome

to

PHP.

Example 2: Using Multiple Delimiters


$str = "apple,banana,cherry";
$delimiters = ",.";
$token = strtok($str, $delimiters);
while ($token !== false) {
    echo $token . "<br>";
    $token = strtok($delimiters);
}

This code will output:

apple

banana

cherry

Things to Note

When using the strtok() function, keep the following considerations in mind:

String Pointer

The strtok() function uses an internal pointer to track the current position of the token. Before using strtok(), make sure the pointer is correctly positioned. You can use the reset() function to reset the pointer to the beginning of the string.

Delimiter Limitation

strtok() only supports a single character or string as a delimiter. If you need to use multiple characters as delimiters, you should consider using the explode() function instead.

End of Tokens

When no more tokens are found, strtok() will return false and move the pointer to the end of the string. To continue splitting the same string, you must reset the pointer to the beginning of the string.

Summary

The strtok() function in PHP is a powerful tool for quickly splitting a string into multiple parts. In this article, we covered the function's syntax, parameters, return values, and provided practical examples. By understanding these basics, you will be able to efficiently handle string splitting in your PHP projects.