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

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

Answer:

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

If the character isn’t found, nothing is echoed

Answer:

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

Answer:

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

Answer:

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

Answer:

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.

Answer:

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, ':') );

Answer:

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.

Answer:

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