PHP Get First 2 Word from String Example

03-Apr-2023

.

Admin

PHP Get First 2 Word from String Example

Hi Dev,

This tutorial is focused on php get first 2 word from string example. if you want to see example of how to get first 2 word from string in php? then you are a right place. you can see get first 2 word from string in php example. you can understand a concept of how to use function to get first 2 word from string in php? .

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

Example 1: Get First Two Word from String


index.php

<?php

$str = "Hello Developer Welcome to Our Website";

//Get first 2 word of a string

$result = explode(" ", $str);

echo $result[0];

echo $result[1];

?>

Output:

Hello

Developer

Example 2: Get First Two Word from String

index.php

<?php

$str = "Hello World i am a web developer";

//Get first 2 word of a string

$result = preg_split("/\s+/", $str);

echo $result[0];

echo $result[1];

?>

Output:

Hello

World

I hope it could help you...

#PHP