Split Sentence Into Words in PHP

In this tutorial we will see How To Split Sentence Into Words in PHP. PHP explode() Function and PHP preg_split() Function can be used to split a complete sentence into separate array of words.

PHP explode() Function

PHP explode() Function splits the string into an array of words or characters.

In this example explode() Function is used to split the sentence into words..

<?php
$string = "Learn PHP on HowToCodeSchool.com";
$array = explode(" ", $string);
echo $array[0];
echo $array[1];
echo $array[2];
echo $array[3];
?>

In above code of PHP, a sentence is split into four words, stored in an array, each word is stored in a separate location in an array.

All four words are separately displayed.

PHP preg_split() Function

PHP preg_split() Function splits a sentence into words with the help of regular expression.

In second example, preg_split() function is also used to split the sentence into four different words.

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

/[^\w]*([\s]+[^\w]*|$)/ is the regular expression used in this example to split the sentence into words.