Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last word of a string

Tags:

string

php

I have tried a few things to get a last part out I done this:

$string = 'Sim-only 500 | Internet 2500'; preg_replace("Sim-Only ^([1-9]|[1-9][0-9]|[1-9][0-9][0-9][0-9])$ | Internet ","",$string AND preg_match("/[^ ]*$/","",{abo_type[1]}) 

The first one won't work and the second returns an array but a realy need string.

like image 585
Roy van Wensen Avatar asked Sep 04 '13 11:09

Roy van Wensen


People also ask

How do you find the last word in an array?

Once you have the array, you are retrieving the last element by taking the value at the last array index (found by taking array length and subtracting 1, since array indices begin at 0).

How can I get the last word of a string in PHP?

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.

How do you call the last word of a string in Python?

You can use . split and pop to retrieve the words from a string. use "0" to get the first word and "-1" for the last word.


2 Answers

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.

like image 164
MLeFevre Avatar answered Oct 12 '22 19:10

MLeFevre


This should work for you:

$str = "fetch the last word from me"; $last_word_start = strrpos ( $str , " ") + 1; $last_word_end = strlen($str) - 1; $last_word = substr($str, $last_word_start, $last_word_end); 
like image 45
hunter Avatar answered Oct 12 '22 20:10

hunter