PHP Get First 5 Word from String Example

03-Apr-2023

.

Admin

PHP Get First 5 Word from String Example

Hi Dev,

In this tutorial, I will show you php get first 5 word from string example. it's simple example of how to get first 5 word from string in php?. it's simple example of get first 5 word from string in php example. Here you will learn how to use function to get first 5 word from string in php? . Alright, let’s dive into the steps.

There are tow example to get First 5 word from strings in PHP. in this example, we will use to the first example explode(), array_slice() and implode() function and second example to use str_word_count() function to get First 5 word. so Let's both the following example with output.

Example 1: Get First Five Word from String


index.php

<?php

$str = 'Welcome to Our Website this Website to Very Useful for Developer ';

$words = explode(' ', $str);

// Get First Five (5) words from String

$five_words = array_slice($words,0,5);

$result = implode(' ',$five_words);

echo $result;

?>

Output:

Welcome to Our Website this

Example 2: Get First Five Word from String

index.php

<?php

$str = "This Website to Very Useful for Developer.";

// Get First Five (5) words from String

$result = implode(' ', array_slice(str_word_count($str, 2), 0, 5));

echo $result;

?>

Output:

This Website to Very Useful

I hope it could help you...

#PHP