The strtok() function in PHP is used to break a string into smaller parts, known as tokens. It works by taking a string and breaking it up into smaller parts, separated by a delimiter character. In this article, we will discuss the strtok() function in detail and how it can be used in PHP.

Understanding the strtok() function

The syntax for using the strtok() function in PHP is as follows:

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

Here, $str is the string that we want to break into smaller parts, and $delimiter is the character that separates these parts. The strtok() function returns the first token found in the string, and subsequent calls to the function with $str set to null will return subsequent tokens until there are no more tokens left.

If the $str parameter is not a string or if the $delimiter parameter is an empty string, the function returns false.

Example Usage

Here is an example usage of the strtok() function in PHP:


$string = "Hello World! How are you?";
$delimiter = " !?";

$token = strtok($string, $delimiter);

while ($token !== false) {
  echo "$token" . "\n";
  $token = strtok($delimiter);

In the example above, we define a string $string and a delimiter $delimiter. We use the strtok() function to break the string into smaller parts, separated by the delimiter characters. We then loop through the tokens and print them out one by one.


The strtok() function in PHP is a powerful tool for breaking a string into smaller parts. It can be used in a wide variety of situations where a string needs to be split up into smaller parts, such as parsing text or data. By understanding how to use the strtok() function, developers can create more efficient and effective PHP applications.

Do you find this helpful?