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?

$string = '​Sim-only 500 ​| Internet 2500';
$pieces = explode(' ', $string);
$last_word = array_pop($pieces);

echo $last_word;

I wouldn't recommend using regular expressions as it's unnecessary, unless you really want to for some reason.

$string = 'Retrieving the last word of a string using PHP.';
preg_match('/[^ ]*$/', $string, $results);
$last_word = $results[0]; // $last_word = PHP.

Using a substr() method would be better than both of these if resources/efficiency/overhead is a concern.

$string = 'Retrieving the last word of a string using PHP.';
$last_word_start = strrpos($string, ' ') + 1; // +1 so we don't include the space in our result
$last_word = substr($string, $last_word_start); // $last_word = PHP.

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.

Last update on August 19 2022 21:50:37 (UTC/GMT +8 hours)

PHP Challenges - 1: Exercise-24 with Solution

Input : PHP Exercises

Write a PHP program to find the length of the last word in a string.

Explanation :

How can i get the last word of a string in php?

Sample Solution :

PHP Code :

1)
        return strlen(substr($s, strrpos($s, ' ') + 1));
        else
        return "Single word";
        
        
}
print_r(length_of_last_word("PHP Exercises")."\n");
print_r(length_of_last_word("PHP")."\n");
print_r(length_of_last_word("")."\n");
print_r(length_of_last_word("  ")."\n");
?>

Sample Output:

9                                                           
Single word                                                 
Blank String                                                
Blank String   

Flowchart:

How can i get the last word of a string in php?

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to find majority element in an array.
Next: Write a PHP program to find the single number which occurs odd number of times and other numbers occur even number of times.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

PHP: Tips of the Day

PHP: 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


  • Exercises: Weekly Top 16 Most Popular Topics
  • SQL Exercises, Practice, Solution - JOINS
  • SQL Exercises, Practice, Solution - SUBQUERIES
  • JavaScript basic - Exercises, Practice, Solution
  • Java Array: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : Conditional Statement
  • HR Database - SORT FILTER: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : String
  • Python Data Types: Dictionary - Exercises, Practice, Solution
  • Python Programming Puzzles - Exercises, Practice, Solution
  • C++ Array: Exercises, Practice, Solution
  • JavaScript conditional statements and loops - Exercises, Practice, Solution
  • C# Sharp Basic Algorithm: Exercises, Practice, Solution
  • Python Lambda - Exercises, Practice, Solution
  • Python Pandas DataFrame: Exercises, Practice, Solution
  • Conversion Tools
  • JavaScript: HTML Form Validation



To find the length of the last word in the string, the PHP code is as follows −

Example

 Live Demo

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.

How can i get the last word of a string in php?

Updated on 17-Aug-2020 12:00:20

  • Related Questions & Answers
  • Python - Find the length of the last word in a string
  • PHP program to find the first word of a sentence
  • Function to find the length of the second smallest word in a string in JavaScript
  • Length of Last Word in C++
  • C++ Program to Find the Length of a String
  • C program to find the length of a string?
  • Finding the length of second last word in a sentence in JavaScript
  • PHP program to find the number of characters in the string
  • C# program to find the index of a word in a string
  • Find the first maximum length even word from a string in C++
  • Python Program to return the Length of the Longest Word from the List of Words
  • C++ program for length of the longest word in a sentence
  • Find the Length of the Longest possible palindrome string JavaScript
  • Program to find length of longest diminishing word chain in Python?
  • PHP – Get the string length using mb_strlen()

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).