How can i get the last word of a string in php?
If you're after the last word in a sentence, why not just do something like this? Show
I wouldn't recommend using regular expressions as it's unnecessary, unless you really want to for some reason.
Using a
it is faster, although it really doesn't make that much of a difference on things like this. If you're constantly needing to know the last word on a 100,000 word string, you should probably be going about it in a different way.
Input : PHP Exercises Write a PHP program to find the length of the last word in a string. Explanation : Sample Solution : PHP Code :
Sample Output: 9 Single word Blank String Blank String Flowchart: PHP Code Editor: Contribute your code and comments through Disqus. Previous: Write a PHP program to find majority element in an array. What is the difficulty level of this exercise? Test your Programming skills with w3resource's quiz. PHP: Tips of the DayPHP: PHP cURL custom headers curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'X-Apple-Tz: 0', 'X-Apple-Store-Front: 143444,12' )); Ref : https://bit.ly/2HgTwMp
To find the length of the last word in the string, the PHP code is as follows − ExampleLive Demo OutputThe 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.
Updated on 17-Aug-2020 12:00:20
How can I get the last part of a string in PHP?Using substr() Method: The substr() is a built-in function in PHP that is used to extract a part of string. Example: For example, if the string is “Akshit loves GeeksForGeeks”. The last character of the string is “s”.
How do I get the last word in a string?To get the last word of a string:
Call the split() method on the string, passing it a string containing an empty space as a parameter. The split method will return an array containing the words in the string. Call the pop() method to get the value of the last element (word) in the array.
How can I get the first word of a string in PHP?echo "The first word of string is: " . $arr [0]; ?> Method 3: Using strstr() Function: The strstr() function is used to search the first occurrence of a string inside another string.
Which script can you use in a regular expression in PHP to remove the last word from a string?Sample Solution: PHP Code: echo preg_replace('/\W\w+\s*(\W*)$/', '$1', $str1).
|