PHP String Exercises: Select first 5 words from the specified string
24. Select First Five Words from a String
Write a PHP script to select first 5 words from the following string.
Sample String : 'The quick brown fox jumps over the lazy dog'
Visual Presentation:

Sample Solution:
PHP Code:
<?php
$my_string = 'The quick brown fox jumps over the lazy dog';
// Define the original string.
echo implode(' ', array_slice(explode(' ', $my_string), 0, 5))."\n";
// Split the string into an array of words, take the first 5 elements, join them with a space, and output the result.
?>
Sample Output:
The quick brown fox jumps
Explanation:
In the exercise above,
- explode(' ', $my_string): Splits the string '$my_string' into an array of words using space ' ' as the delimiter.
- array_slice(..., 0, 5): Retrieves the first 5 elements from the array obtained from the explode() function.
- implode(' ', ...): Joins the selected elements from the array into a string with space ' ' as the glue.
- Finally, it echoes out the modified string, which consists of the first 5 words of the original string separated by spaces.
Flowchart :

For more Practice: Solve these Related Problems:
- Write a PHP script to extract the first five words from a sentence and output them without any extra spaces.
- Write a PHP function to split a sentence into an array, then join the first five elements with a space and return the result.
- Write a PHP program to validate a string to have at least five words and then output the first five words using array_slice().
- Write a PHP script to handle a sentence with punctuation and output the first five words, correctly preserving word order.
Go to:
PREV : Replace Multiple Characters in a String.
NEXT : Remove Commas from Numeric String.
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.