How to Get First Word from String in PHP?
Hi Friends,
Here, I will show you php get first word from string. you will learn how to get first word from string in php. you can see php get first word from string example. It's a simple example of get first word from string php. you will do the following things for php get first word from string.
we will use strtok() php function to get first word from string. i will give you very simple examples to get first word from string in php.
Example 1: PHP Get First Word from String
index.php
<?php
/* Declare string variable */
$string = "Welcome to ItSolutionStuff.com!";
/* get First word of string */
$firstWord = strtok($string, " ");
/* Echo resulted string */
var_dump($firstWord);
?>
Output:
string(7) "Welcome"
Example 2: PHP Get Last Word from String
index.php
<?php
/* Declare string variable */
$string = "Welcome to ItSolutionStuff.com!";
/* get Last word of string */
$split = explode(" ", $string);
$lastWord = $split[count($split)-1];
/* Echo resulted string */
var_dump($lastWord);
?>
Output:
string(19) "ItSolutionStuff.com"
Example 3: PHP Get First and Last Word from String
index.php
<?php
/* Declare string variable */
$string = "Welcome to ItSolutionStuff.com";
/* get First and Last word of string */
$firstWord = strtok($string, " ");
$split = explode(" ", $string);
$lastWord = $split[count($split)-1];
/* Echo resulted string */
var_dump($firstWord);
var_dump($lastWord);
?>
Output:
string(7) "Welcome"
string(19) "ItSolutionStuff.com"
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Get Last 2, 3, 4, 5, 7 Characters of a String in PHP?
- PHP String Count Specific Character Example
- How to Upgrade PHP Version from 8.1 to 8.2 in Ubuntu?
- PHP Get First 2, 3, 4, 5, 10 Character from String Example
- How to Get First and Last Character from String in PHP?
- How to Get Last Character from String in PHP?
- How to Get First Character from String in PHP?
- How to Remove Last Character from String in PHP?
- How to Remove First Character from String in PHP?
- PHP Remove First and Last Character from String Example
- How to Check Query Execution Time in PHP?
- How to Remove Special Characters from String in PHP?
- How to Check If Date is Future Date in PHP?