How to Split a Sentence into Words in PHP

To split a string into individual words, you can use the PHP function – strtok( $str, $token ). It takes two parameters: the string and the characters by which the string will be divided into parts.

strtok() splits the string $str into substrings (tokens), using the characters from $token as delimiters.

For example, the string "This is an example string" can be split into individual words using a space as a delimiter.

$string = "God rewarded him with a syllable and a humble mind,
Moses became a famous gentleman...";

$sep = " \n\t";

// We use space, tab, and newline as delimiters
$token = strtok( $string, $sep );

while ( $token !== false ) {
	echo "word = $token\n";
	$token = strtok( $sep );
}

/*
word = God
word = rewarded
word = him
word = with
word = a
word = syllable
word = and
word = a
word = humble
word = mind,
word = Moses
word = became
word = a
word = famous
word = gentleman...
*/

Note that the original string is only passed in the first call to strtok(). Subsequent calls only pass the delimiters, as this function saves the original string and remembers the position in this string between calls. To work with a new string, you need to call the function again with two arguments.

Please note that you can use multiple delimiters in the token parameter. The string will be split by any character found in this parameter.