ItSolutionStuff.com

How to Get Last Word from String in PHP?

By Hardik Savani • May 14, 2024
PHP

Hello Artisan,

In this tutorial, you will learn php get last word from string. I’m going to show you about how to get last word from string in php. This example will help you php get last word from string example. step by step explain get last word from string php.

we will use explode() php function to get Last word from string. i will give you very simple examples to get Last word from string in php.

Example 1: 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 2: 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 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...

Tags: PHP
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

šŸ“ŗ Subscribe on YouTube

We Are Recommending You

ā˜…

How to Remove Last 2, 3, 4, 5, 7 Characters of a String in PHP?

Read Now →
ā˜…

How to Get Last 2, 3, 4, 5, 7 Characters of a String in PHP?

Read Now →
ā˜…

PHP String Count Specific Character Example

Read Now →
ā˜…

How to Upgrade PHP Version from 8.1 to 8.2 in Ubuntu?

Read Now →
ā˜…

PHP Get First 2, 3, 4, 5, 10 Character from String Example

Read Now →
ā˜…

How to Get First and Last Character from String in PHP?

Read Now →
ā˜…

How to Get Last Character from String in PHP?

Read Now →
ā˜…

How to Get First Character from String in PHP?

Read Now →
ā˜…

How to Remove Last Character from String in PHP?

Read Now →
ā˜…

How to Remove First Character from String in PHP?

Read Now →
ā˜…

PHP Remove First and Last Character from String Example

Read Now →
ā˜…

How to Check Query Execution Time in PHP?

Read Now →
ā˜…

How to Add Seconds to Time in PHP?

Read Now →