Unknown Error
Unknown Error

Reputation: 797

How do I retrieve last word or character in PHP

Example string

$string = 'how-do-i-retrieve-last-word'
$string = 'how-do-i-retrieve-last-word-2'
$string = 'how-do-i retrieve-last word-123'
$string = 'how do i retrieve last word test'

I want to retrieve a last word on string above and the result should be :

word
2
123
test

Upvotes: 1

Views: 675

Answers (4)

Petah
Petah

Reputation: 46050

function lastWord($string) {
    $pos = max(strripos($string, ' '), strripos($string, '-')) + 1;
    return substr($string, -(strlen($string) - $pos));
}

var_dump(lastWord('how-do-i-retrieve-last-word'));
var_dump(lastWord('how-do-i-retrieve-last-word-2'));
var_dump(lastWord('how-do-i retrieve-last word-123'));
var_dump(lastWord('how do i retrieve last word test'));

Gives you:

string 'word' (length=4)
string '2' (length=1)
string '123' (length=3)
string 'test' (length=4)

Upvotes: 1

Shomz
Shomz

Reputation: 37701

preg_match_all('/\w+/', $string, $res);

The $res array will contain all the words from the string, so you can easily select the last one.

Upvotes: 1

user784637
user784637

Reputation: 16122

$stringAfterHyphen = substr($string, -1, strpos($string, '-'));

Let me explain. The substr function takes your string, starts at the last character and keeps going to the left until it reaches a hyphen.

Upvotes: 1

anubhava
anubhava

Reputation: 785128

You can use this regex with preg_match:

/\b(\w+)$/

Code:

if (preg_match('/\b(\w+)$/', $str, $m))
   var_dump($m[1]); // will print your last word

Upvotes: 6

Related Questions