We are given a string. We are required to write a program in PHP to find the length of the last word in the string using inbuilt functions.
We have already discussed approach of solving this problem here. This article discusses the PHP solution to the problem.
Input : "php exercises" Output : 9 Input : "geeks for geeks" Output : 5
We will mainly use these three inbuilt function in PHP to solve this problem:
- substr() Function: This inbuilt function in PHP is used to extract a part of string.
- strrpos() Function: This inbuilt function in PHP is used to find the last position of string in original or in another string. It returns the integer value corresponding to position of last occurrence of the string, also it treats uppercase and lowercase characters uniquely.
- strlen() Function: This inbuilt function in PHP is used to find the length of a string.
The idea to solve this problem using the above mentioned inbuilt function is to first find the position of last occurring space in the string using the strpos() function. After getting the position of last occurring space we can easily get the last word in the string using the substr() function and store this in a new string variable. At last, we can use the strlen() function to find the length of the last word in the string.
- What is the difference between “word-break: break-all” versus “word-wrap: break-word” in CSS ?
- Last-child and last-of-type selector in SASS
- How to replace a word inside a string in PHP ?
- How to get the last n characters of a PHP string?
- How to get the first word of a sentence in PHP?
- PHP | Ds\Sequence last() Function
- PHP | Print the last value of an array without affecting the pointer
- Determine the first and last iteration in a foreach loop in PHP?
- PHP | Ds\Map last() Function
- PHP | Ds\Vector last() Function
- PHP | Ds\Set last() Function
- PHP | Ds\Deque last() Function
- How to get last day of a month from date in PHP ?
- PHP | Program to check a string is a rotation of another string
- CSS | word-spacing Property
- CSS | word-break Property
- CSS | word-wrap Property
- How to validate if input in input field must contains a seed word using express-validator ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : nidhi_biet