$string = "Hello World Again".
echo strrchr($string , ' '); // Gets ' Again'
Now I want to get "Hello World" from the $string开发者_如何学Go
[The substring before the last occurrence of a space ' ' ]. How do I get it??
$string = "Hello World Again";
echo substr($string, 0, strrpos( $string, ' ') ); //Hello World
If the character isn't found, nothing is echoed
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);
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));
$myString = "Hello World Again";
echo substr($myString, 0, strrpos($myString, " "));
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
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));
}
<?php
$str = "Hello World!";
echo $str . "<br>";
echo chop($str,"World!");
// output - Hello
?>
精彩评论