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

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));