Last Updated:

PHP : Break a line into words

PHP


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");
}
var_dump($array_words);

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:


Result:
<?php
$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);
}
var_dump($array_words);

array(5) {
[0]=>
string(10) "Text"
[1]=>
string(6) "for"
[2]=>
string(16) "validation"
[3]=>
string(14) "functions"
[4]=>
string(6) "strtok"

}