Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP program to find the length of the last word in the string
In PHP, you can find the length of the last word in a string by locating the last space character and extracting the substring that follows it. This approach uses built-in string functions like strrpos() and substr().
Example
Here's a PHP function that finds the length of the last word in a string ?
<?php
function last_word_len($my_string){
$position = strrpos($my_string, ' ');
if(!$position){
$position = 0;
} else {
$position = $position + 1;
}
$last_word = substr($my_string, $position);
return strlen($last_word);
}
print_r("The length of the last word is ");
print_r(last_word_len('Hey')."<br>");
print_r("The length of the last word is ");
print_r(last_word_len('this is a sample')."<br>");
?>
The length of the last word is 3 The length of the last word is 6
How It Works
The function last_word_len() takes a string as parameter and follows these steps ?
$position = strrpos($my_string, ' ');
if(!$position){
$position = 0;
} else{
$position = $position + 1;
}
The strrpos() function finds the position of the last occurrence of a space character. If no space is found (single word), the position is set to 0. Otherwise, it's incremented by 1 to point to the character after the space.
The substr() function extracts the last word starting from the calculated position, and strlen() returns its length.
Conclusion
This method efficiently finds the last word's length by locating the last space and measuring the remaining substring. It handles both single words and multi-word strings correctly.
