w3resource
php Programming Exercies

PHP String Exercises: Select first 5 words from the specified string

PHP String: Exercise-24 with Solution

Write a PHP script to select first 5 words from the following string.

Sample String : 'The quick brown fox jumps over the lazy dog'

Pictorial Presentation:

PHP String Exercises: Select first 5 words from the specified string

Sample Solution:

PHP Code:

<?php
$my_string = 'The quick brown fox jumps over the lazy dog';
echo implode(' ', array_slice(explode(' ', $my_string), 0, 5))."\n";
?>

Sample Output:

The quick brown fox jumps 

Flowchart :

Flowchart: Select first 5 words from the specified string

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP script to replace multiple characters from the specified string.
Next: Write a PHP script to remove comma(s) from the specified numeric string.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming