How to catch last word of a string in PHP?

Asked

Viewed 2,757 times

0

For example: "JOHN DOE OF SUCH". I wish to take only the word "SUCH".

  • 1

    Did something happen to exchange acceptance? Have you done all the necessary tests and seen that the one you accepted now has problems in some situations? The example itself posted does not work. But look at the result: https://ideone.com/Ka7p7f

  • I do not understand a good and genuine question like this being negativated, I do not understand why there are answers to the question with good punctuation and the question no, it is as if here people do not care with those who have doubts only with those who have the knowledge.

  • The only thing I didn’t understand was that those who closed also answered the question. You will understand...

4 answers

8

The simplest and somewhat naive way would be this (I do not guarantee that meets any situation, but question does not say much:

$palavras = explode(' ', 'José da Silva');
echo $palavras[count($palavras) - 1];

You use a function that already breaks words based on space by generating a array, then just take the last element of it.

According to the bfavaretto below can do a little better and so a little less naive:

$texto = 'José da Silva';
$texto = trim($texto);
echo substr($texto, strrpos($texto, ' ') + 1);

Behold working in the ideone. And in the rep.it. Also put on the Github for future reference.

  • "Simple" depends on the point of view. I find it simpler, and I imagine until you agree: substr($texto, strrpos($texto, ' ')).

  • I agree, I don’t even remember that strrpos() :) But it would be naive too.

  • Naive was I have wrong start index by 1 :D. It would need to be strrpos($texto, ' ')+1 not to take up their own space.

  • @bfavaretto is true, I was wrong because of you :P Now it’s ok. I was thinking about taking performance test, but I already have an idea, and it’s not worth the effort.

  • strrpos is the best option. There’s no reason to complicate by blowing up space.

6


Using the function strrchr() see in ideone

$string ="Eu não recomendaria o uso de expressões regulares, pois é desnecessário, a menos que você realmente queira, por algum motivo";

$ultima_palavra = strrchr($string,' ');

echo $ultima_palavra;

strrchr() - returns the part that starts at last occurrence

Another way:

$string = 'JOÃO FULANO DE TAL';
$partes = explode(' ', $string);
$ultima_palavra = array_pop($partes);

echo $ultima_palavra;

The explode() separates a string into an array of several smaller strings based on a divisor character, which can be a point, a comma, or any other character or string (in your case a space). Your syntax is like this:

explode( separador,string,limite )
  • separador: The character that must be found inside the string to split it;
  • string: The text in which we want to divide;
  • limite: It is the number of times the command must split the string. This parameter is optional and if not informed the division will be done by every string.

    array_pop() extracts and returns the last element of the array

2

Can use preg_match() with a regular expression:

preg_match("|\w+?$|", $string, $ultima);

Will always pick up the last characters1 from the end of the text backwards ($) until alphanumeric or underscore (\w), in the case, the space before "SUCH".

<?
$string = "JOÃO FULANO DE TAL";
preg_match("|\w+?$|", $string, $ultima);
echo $ultima[0]; // imprime: TAL
?>

1 It will only work with words without special characters.

2

Complemented the answers already given; there are some ways to do it, none properly "right". What can be done is to isolate and leave the most clean possible the code.

The first example would be to use Regex:

$string = "mauro é perfeito";

preg_match("/[\w\-]+$/", $string, $matches);

echo $matches[0]; //perfeito

But since nothing is perfect (neither do I), use regex is not the simplest way, but in relation to the explode() he stands "in front" in question XGH.

The second way, using the explode() would be using the method end() to obtain the last occurrence.

$string = "mauro é perfeito";
$string = explode(" ", $string );

$last_word = end($string);

echo $last_word; //perfeito

  • The end function only works on variables because it asks for an argument by reference. This will generate an error in some versions of PHP

  • Generates a notice, but as it is for didactic purposes, I see no problem.

  • Well, the E_NOTICE indicates that something is wrong. I think it is valid to simply add the result of explode variable. Understand as constructive criticism: If the example is didactic, it has to be right.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.