Split String by Delimiter using strtok() Function

The strtok() function to tokenize the string based on a specified delimiter (comma in this case) iteratively until no more tokens are found.

PHP




<?php
 
$string = "apple,orange,banana";
 
// Use strtok to tokenize the
// string based on commas
$token = strtok($string, ',');
 
// Output each token until there
// are no more
while ($token !== false) {
    echo $token . "\n";
    $token = strtok(',');
}
 
?>


Output

apple
orange
banana

How to Split String by Delimiter/Separator in PHP?

Given a String, the task is to split the string by the delimiter. In this case, the delimiter is comma “,”.

Examples:

Input: apple,orange,banana
Output:
apple
orange
banana

There are seven approaches to split the string, these are:

Table of Content

  • Split String by Delimiter using explode() Function
  • Split String by Delimiter using preg_split() Function and Regular Expression
  • Split String by Delimiter using strtok() Function
  • Split String by Delimiter using sscanf() Function
  • Split String by Delimiter using substr() and strpos() Functions

Similar Reads

Split String by Delimiter using explode() Function

The explode() function splits a string into an array based on a specified delimiter (in this case, a comma)....

Split String by Delimiter using preg_split() Function and Regular Expression

...

Split String by Delimiter using strtok() Function

The preg_split() function with a regular expression to split the string into an array, providing more flexibility for complex delimiter patterns....

Split String by Delimiter using sscanf() Function

...

Split String by Delimiter using substr() and strpos() Functions

The strtok() function to tokenize the string based on a specified delimiter (comma in this case) iteratively until no more tokens are found....

Contact Us