To Get Second And Third Word from Strings in PHP we use PHP’s inbuilt function named as explode() function. Before we check the source code to get any word from any position using PHP, we do some introduction about PHP explode function.

Introduction to Explode Function in PHP
The explode()
function breaks the given string into the array.
Syntax of Explode function
explode(separator,string,limit)
- Separator must not be blank.
- Any type of string.
- Limit of an array element according to your string.
Example:
1 2 3 4 5 6 |
// zero limit $str = 'php,coder,tech,explode'; print_r(explode(',',$str,0)); print_r(explode(',',$str,2)); |
Array ( [0] => php,coder,tech,explode )
Array ( [0] => php [1] => coder,tech,explode )
To know more about PHP explode function you can check here: https://phpcoder.tech/php-explode-function/
Now we check how to get Second And Third Word from Strings in PHP,
Source code to get Second And Third Word from Strings in PHP
1 2 3 4 5 6 |
<?php $myvalue = 'Test Word COUNT in PHP'; $arr = explode(' ',trim($myvalue)); echo "Second Word: ".$arr[1]; echo "<br>"; echo "Third Word: ".$arr[2]; |
Output:
1 2 |
Second Word: Word Third Word: COUNT |
PHP Get the First 5 Words From String
1 2 3 4 |
<?php $dummyText = "Lorem ipsum dolor sit amet consectetur adipisicing elit"; echo implode(' ', array_slice(str_word_count($dummyText, 2), 0, 5)); |
Output:
Lorem ipsum dolor sit amet
Code Explanations:
- We use
str_word_count()
function to check an array where the key is the position of the word in the string, and the value is the actual word. array_slice()
it returns 1 to 5 words from the given string.
Check the complete use and explanations of explode function from the PHP official site, https://www.php.net/manual/en/function.explode.php
You can check all the code using our online compiler, https://phpcoder.tech/php-online-editor/
Also Check:
- Export MySQL Data to Excel in PHP Using Ajax
- Login with Google Account using PHP Step by Step
- How to Embed PDF in Website Using HTML
- 2 Ways to Open URL in New Tab Using JavaScript
Happy Coding..!
One Reply to “Get Second And Third Word from Strings in PHP”