
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Length of the Last Word in a String using PHP
To find the length of the last word in the string, the PHP code is as follows −
Example
<?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')."
"); print_r("The length of the last word is "); print_r(last_word_len('this is a sample')."
"); ?>
Output
The length of the last word is 3 The length of the last word is 6
A PHP function named ‘last_word_len’ is defined, that takes a string as the parameter −
function last_word_len($my_string) { // }
The first occurrence of the space inside another string is found by using the ‘strrpos’ function. If that position is present, it is assigned to 0. Otherwise, it is incremented by 1 −
$position = strrpos($my_string, ' '); if(!$position){ $position = 0; } else{ $position = $position + 1; }
The substring of the string, based on the position is found, and the length of this string is found and returned as output. Outside this function, the function is called by passing the parameter, for two different samples and the output is printed on the screen.
Advertisements