Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,040 questions

55,897 answers

573 users

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
...