php字符串函数在最后一次出现字符之前获取子字符串

pta*_*mzz 35 php

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

如果找不到该字符,则不会回显任何内容

  • @ Arvind07是的,这是正确的`:`将找不到,因为它不在字符串中,也不在问题中!?同样适用于您选择的不在字符串中的任何字符.你想说什么? (5认同)

sdl*_*rhc 13

这是一种廉价的方法,但你可以拆分,弹出,然后加入以完成它:

$string = 'Hello World Again';
$string = explode(' ', $string);
array_pop($string);
$string = implode(' ', $string);
Run Code Online (Sandbox Code Playgroud)


zaf*_*zaf 7

一个(好的和冷静的)方式:

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

  • @sdleihssirhc感谢写这篇评论,因为否则人们现在不知道谁是这里最快的孩子.那是对的,投票给我的人. (2认同)

Til*_*ill 5

$myString = "Hello World Again";
echo substr($myString, 0, strrpos($myString, " "));
Run Code Online (Sandbox Code Playgroud)


R T*_*R T 5

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