How To Separate A Sentence Into Words In PHP

This post will show you how PHP can break a sentence into words. PHP explode() and preg_split() functions can break a complete sentence into a list of words that can be used separately.

explode() Function

The string is broken into an array of words or characters using the explode() function of the PHP programming language.


In this demonstration, the explode() function is used to break the string into separate words.


<?php
$string = "Learn Coding on CodesBright";
$array = explode(" ", $string);
echo $array[0]."\n";
echo $array[1]."\n";
echo $array[2]."\n";
echo $array[3]."\n";
?>



In the PHP code shown above, a sentence is broken into four words and stored in an array, with each word having its spot in the array.


All four words are shown separately.


Output

Learn
Coding
on
CodesBright

preg_split() Function

With the help of regular expression and the preg_split() function, we can separate a string into words. Check the following code to see how the string is separated using preg_split().


<?php
$string = "Learn Coding on CodesBright";
$array = preg_split("/[^\w]*([\s]+[^\w]*|$)/", $string, -1, PREG_SPLIT_NO_EMPTY);
echo $array[0];
echo $array[1];
echo $array[2];
echo $array[3];
?>



In the above example, the regular expression separates the string into words.


Output

Learn
Coding
on
CodesBright