How to get the last word from a string in PHP

5 Answers

0 votes
$s = "php java c# python c++";
 
$last_word = substr($s, strrpos($s, ' '));
      
echo $last_word;
 
 
 
   
/*
run:
 
c++
 
*/

 



answered Sep 6, 2019 by avibootz
0 votes
$s = "php java c# python c++";
   
$arr = explode(' ', $s);

$last_word = $arr[count($arr) - 1];
      
echo $last_word;
 
 
 
   
/*
run:
 
c++
 
*/

 



answered Sep 6, 2019 by avibootz
0 votes
$s = "php java c# python c++";
   
$arr = preg_split('/ / ', $s);

$last_word = $arr[count($arr) - 1];
      
echo $last_word;
 
 
 
   
/*
run:
 
c++
 
*/

 



answered Sep 6, 2019 by avibootz
0 votes
$s = "php java c# python c++";

$arr = explode(' ', $s);

$last_word = array_pop($arr);

echo $last_word;




/*
run:
  
c++
  
*/

 



answered Jul 27, 2020 by avibootz
0 votes
/**
 * Returns the last word from a given string.
 *
 * @param string $input The input string.
 * @return string The last word, or an empty string if none found.
 */
function getLastWord(string $input): string {
    // If the string is empty or contains only whitespace, return empty string
    if (trim($input) === "") {
        return "";
    }

    // Remove leading and trailing spaces
    $input = trim($input);

    // Find the last space in the string
    $pos = strrpos($input, " ");

    // If a space was found, return the substring after it; otherwise return the whole string
    return $pos !== false ? substr($input, $pos + 1) : $input;
}


// Test cases
$tests = [
    "vb.net javascript php c c++ python c#",
    "",
    "c#",
    "c c++ java ",
    "  "
];

foreach ($tests as $index => $t) {
    echo ($index + 1) . ". " . getLastWord($t) . PHP_EOL;
}


/*
run:

1. c#
2. 
3. c#
4. java
5. 

*/

 



answered Mar 27 by avibootz
edited Mar 27 by avibootz
...