$string = "Hello World Again".
echo strrchr($string , ' '); // Gets ' Again'
Run Code Online (Sandbox Code Playgroud)
现在我想从$string
[最后一次出现空格'前的子字符串' 获得"Hello World" .我怎么得到它?
meo*_*ouw 47
$string = "Hello World Again";
echo substr($string, 0, strrpos( $string, ' ') ); //Hello World
Run Code Online (Sandbox Code Playgroud)
如果找不到该字符,则不会回显任何内容
sdl*_*rhc 13
这是一种廉价的方法,但你可以拆分,弹出,然后加入以完成它:
$string = 'Hello World Again';
$string = explode(' ', $string);
array_pop($string);
$string = implode(' ', $string);
Run Code Online (Sandbox Code Playgroud)
一个(好的和冷静的)方式:
$string = "Hello World Again";
$t1=explode(' ',$string);
array_pop($t1);
$t2=implode(' ',$t1);
print_r($t2);
Run Code Online (Sandbox Code Playgroud)
其他(更棘手的)方式:
$result = preg_replace('~\s+\S+$~', '', $string);
Run Code Online (Sandbox Code Playgroud)
要么
$result = implode(" ", array_slice(str_word_count($string, 1), 0, -1));
Run Code Online (Sandbox Code Playgroud)
$myString = "Hello World Again";
echo substr($myString, 0, strrpos($myString, " "));
Run Code Online (Sandbox Code Playgroud)
strripos \xe2\x80\x94 查找字符串中不区分大小写的子字符串最后一次出现的位置
\n\n $string = "hello world again";\n echo substr($string, 0, strripos($string, \' \')); // Hello world\n
Run Code Online (Sandbox Code Playgroud)\n