Last Updated:

PHP : Break a line into words


You can break a string into words using the strtok function.

This function takes 2 parameters.

The first parameter is the string to be processed.

The second parameter is a string containing characters by which the string will be divided into words.

The string included in the first parameter:

The array of the received words from the string:

The delimiter characters will be: space, tab and line wrapping:

Split and write the value to the variable $tok:

Only the first word will be written into the variable $tok. Retrieving an array of string milestones will be described later.

It is believed that the original string is passed when the function is first called.
In subsequent calls, only delimiter characters are passed, since this function remembers the passed string and remembers the positions in this line.

To work with a new line, you must call the function again with two parameters.

We get an array with the words defined in the line:

Display the result:

The value of the result received on the screen:
$string = "Text\for\testing strtok";
$array_words = array();
$separator = " \t\n";
$tok = strtok($string, $separator);
$tok = strtok(" \t\n");
while($tok) {
    $array_words[] = $tok;
    $tok = strtok(" \t\n");

array(5) { [0]=> string(5) "Text" [1]=> string(3) "for" [2]=> string(8) "validation" [3]=> string(7) "functions" [4]=> string(6) "strtok" }

Example source code:

$string = "Text\t to \ntest the strtok function";
$separator = "\t\n";

$array_words = [];
$tok = strtok($string, $separator);

while($tok) {
     $array_words[] = $tok;
     $tok = strtok($separator);

array(5) {
string(10) "Text"
string(6) "for"
string(16) "validation"
string(14) "functions"
string(6) "strtok"