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

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

Posted by: admin April 23, 2020 Leave a comment

$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??

How to&Answers:

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);
$string = implode(' ', $string);


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

If the character isn’t found, nothing is echoed


One (nice and chilled out) way:

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

Other (more tricky) ways:

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


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


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


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


You can use a combination of strrpos, which gets the position of the last instance of a given string within a string, and substr to return the value.


The correct implementation should be:

$string = "Hello World Again";
$pos = strrpos( $string, ' ');
if ($pos !== false) {
    echo substr($string, 0, $pos ); //Hello World

Otherwise if the character is not found it will print nothing. See following case:

$string = "Hello World Again";
//prints nothing as : is not found and strrpos returns false.
echo substr($string, 0, strrpos( $string, ':') );


You could just use:

$string = "Hello World Again";
echo preg_replace('# [^ ]*$', '', $string);

This will work regardless of whether the character occurs in the string or not. It will also work if the last character is a space.


function cutTo($string, $symbol) {
    return substr($string, 0, strpos($string, $symbol));