![](/img/trans.png)
[英]Insert before the last occurrence of a specific character in a string in PHP
[英]php string function to get substring before the last occurrence of a character
$string = "Hello World Again".
echo strrchr($string , ' '); // Gets ' Again'
现在我想从$string
[最后一次出现空格 ' ' 之前的子$string
] 中获取“Hello World”。 我怎么得到它??
$string = "Hello World Again";
echo substr($string, 0, strrpos( $string, ' ') ); //Hello World
如果未找到该字符,则不回显任何内容
这是一种廉价的方法,但您可以拆分、弹出,然后加入以完成它:
$string = 'Hello World Again';
$string = explode(' ', $string);
array_pop($string);
$string = implode(' ', $string);
一种(好的和冷静的)方式:
$string = "Hello World Again";
$t1=explode(' ',$string);
array_pop($t1);
$t2=implode(' ',$t1);
print_r($t2);
其他(更棘手的)方法:
$result = preg_replace('~\s+\S+$~', '', $string);
或者
$result = implode(" ", array_slice(str_word_count($string, 1), 0, -1));
strripos — 查找不区分大小写的子字符串在字符串中最后一次出现的位置
$string = "hello world again";
echo substr($string, 0, strripos($string, ' ')); // Hello world
$myString = "Hello World Again";
echo substr($myString, 0, strrpos($myString, " "));
正确的实现应该是:
$string = "Hello World Again";
$pos = strrpos( $string, ' ');
if ($pos !== false) {
echo substr($string, 0, $pos ); //Hello World
}
否则,如果找不到该字符,它将不打印任何内容。 见以下案例:
$string = "Hello World Again";
//prints nothing as : is not found and strrpos returns false.
echo substr($string, 0, strrpos( $string, ':') );
你可以只使用:
$string = "Hello World Again";
echo preg_replace('# [^ ]*$', '', $string);
无论字符是否出现在字符串中,这都将起作用。 如果最后一个字符是空格,它也将起作用。
function cutTo($string, $symbol) {
return substr($string, 0, strpos($string, $symbol));
}
<?php
$str = "Hello World!";
echo $str . "<br>";
echo chop($str,"World!");
// output - Hello
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.