Roy van Wensen
Roy van Wensen

Reputation: 610

Get the last word of a string

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.

Upvotes: 39

Views: 75943

Answers (10)

Hashim Aziz
Hashim Aziz

Reputation: 6062

This is the cleanest solution I've come across, using the lesser-known function strrchr (don't ask me what it stands for):

$last = ltrim(strrchr($string, " "));

Note that strrchr returns false if a match can't be found (i.e. the string is empty), so if you need to check for this use an Elvis operator rather than a null coalescing operator:

$last = ltrim(strrchr($string, " ")) ?: "No matches found";

Upvotes: 1

One-line solution using regexp:

preg_replace('/.*\s/', '', $string);

This suppress everything ending by a space, and since regexp are always matched "as long as possible", this will match everything but the last word. This has also the advantage on working with any "space" character (tab, newline...).

But the best performance/ressources consumption solution is (does not work if only one word):

substr($string, strrpos($string, ' ') + 1);

Upvotes: 0

Appoodeh
Appoodeh

Reputation: 132

Just use this function

function last_word($string)
{
    $pieces = explode(' ', $string);
    return array_pop($pieces);
}

Upvotes: -2

Indrek
Indrek

Reputation: 887

The existing solutions all work fine, but I wanted a one-liner. explode() will split a sentence into words, but trying to pass it directly into array_pop() or end() gives a "Only variables should be passed by reference" notice. array_slice() to the rescue:

$string = 'Sim-only 500 | Internet 2500';
echo array_slice(explode(' ', $string), -1)[0];

Upvotes: 3

SubjectCurio
SubjectCurio

Reputation: 4872

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.

Upvotes: 78

Sleek Geek
Sleek Geek

Reputation: 4686

Here is another way to get the last word from a string

$my_string = "fetch the last word from me";
 
// Explode the string into an array
$my_string = explode(" ", $my_string);

// target the last word with end() function 
$my_string = end($my_string);

echo $my_string;

Result me

Upvotes: 1

Elron
Elron

Reputation: 1455

If you want to wrap the last word with a span:

<?php
/**
 * Wrap last word with span
 * @author: Elron
 * https://stackoverflow.com/questions/18612872/get-the-last-word-of-a-string
 */
function wrap_last_word($string) {
    // Breaks string to pieces
    $pieces = explode(" ", $string);

    // Modifies the last word
    $pieces[count($pieces)-1] = '<span class="is-last-word">' . $pieces[count($pieces)-1] . '</span>';

    // Returns the glued pieces
    return implode(" ", $pieces);
}

wrap_last_word('hello this is wrapped');
// returns this:
// hello this is <span class="is-last-word">wrapped</span>

Upvotes: 3

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

There you go a generic function to get last words from string

public function get_last_words($amount, $string)
{
    $amount+=1;
    $string_array = explode(' ', $string);
    $totalwords= str_word_count($string, 1, 'àáãç3');
    if($totalwords > $amount){
        $words= implode(' ',array_slice($string_array, count($string_array) - $amount));
    }else{
        $words= implode(' ',array_slice($string_array, count($string_array) - $totalwords));
    }

    return $words;
}
$string = '​Sim-​only 500 | Internet 2500​';
echo get_last_words(1,  $string );

Upvotes: 1

hunter
hunter

Reputation: 91

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

Upvotes: 9

ranieuwe
ranieuwe

Reputation: 2296

It depends on what you try to do (it is hard to understand from your description) but to get the last word from a string you can do:

$split = explode(" ", $string);

echo $split[count($split)-1];

See How to obtain the last word of a string for more information.

Upvotes: 6

Related Questions