php string function to get substring before the last occurrence of a character

$string = "Hello World Again".
echo strrchr($string , ' '); // Gets ' Again'

Now I want to get "Hello World" from the $string [The substring before the last occurrence of a space ' ' ]. How do I get it??


Solution 1:

$string = "Hello World Again";
echo substr($string, 0, strrpos( $string, ' ') ); //Hello World

If the character isn't found, nothing is echoed

Solution 2:

This is kind of a cheap way to do it, but you could split, pop, and then join to get it done:

$string = 'Hello World Again';
$string = explode(' ', $string);
array_pop($string);
$string = implode(' ', $string);

Solution 3:

One (nice and chilled out) way:

$string = "Hello World Again";
$t1=explode(' ',$string);
array_pop($t1);
$t2=implode(' ',$t1);
print_r($t2);

Other (more tricky) ways:

$result = preg_replace('~\s+\S+$~', '', $string);

or

$result = implode(" ", array_slice(str_word_count($string, 1), 0, -1));

Solution 4:

strripos — Find the position of the last occurrence of a case-insensitive substring in a string

 $string = "hello world again";
 echo substr($string, 0, strripos($string, ' ')); // Hello world

Solution 5:

$myString = "Hello World Again";
echo substr($myString, 0, strrpos($myString, " "));