PHP:如何从字符串中删除最后一个单词?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29428459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: How can I remove from String the last word?
提问by Kiuki
How can I remove, with PHP, the last word from a String?
如何使用 PHP 从字符串中删除最后一个单词?
For example the string "Hi, I'm Gian Marco"
would become "Hi, I'm Gian"
.
例如,字符串"Hi, I'm Gian Marco"
将变为"Hi, I'm Gian"
.
回答by Ahmed Ziani
try with this :
试试这个:
$txt = "Hi, I'm Gian Marco";
$str= preg_replace('/\W\w+\s*(\W*)$/', '', $txt);
echo $str
out put
输出
Hi, I'm Gian
回答by Sameed Alam Qureshi
check this
检查这个
<?php
$str ='"Hi, I\'m Gian Marco" will be "Hi, I\'m Gian"';
$words = explode( " ", $str );
array_splice( $words, -1 );
echo implode( " ", $words );
?>
source : Remove last two words from a string
source :从字符串中删除最后两个单词
回答by Nishad Up
You can do it with regular expression. (see answer of Ahmed Ziani.)
你可以用正则表达式来做到这一点。(见Ahmed Ziani 的回答。)
However, in PHP you can also do it using some inbuilt function. see the code below
但是,在 PHP 中,您也可以使用一些内置函数来完成。看下面的代码
$text = "Hi, I'm Gian Marco";
$last_space_position = strrpos($text, ' ');
$text = substr($text, 0, $last_space_position);
echo $text;
回答by cpugourou
The current solution is ok if you do not know the last word and the string length is short.
如果您不知道最后一个单词并且字符串长度很短,则当前的解决方案是可以的。
In case you do know it, for instance when looping a concat string for a query like this:
如果您确实知道它,例如在为这样的查询循环 concat 字符串时:
foreach ($this->id as $key => $id) {
$sql.=' id =' . $id . ' OR ';
}
A better solution:
更好的解决方案:
$sql_chain = chop($sql_chain," OR ");
Be aware that preg_replace with a regex is VERYslow with long strings. Chop is 100 times faster in such case and perf gain can be substantial.
请注意,带有正则表达式的 preg_replace对于长字符串非常慢。在这种情况下,Chop 的速度要快 100 倍,而且性能增益可能很大。
回答by lakshman
This code may help you :
此代码可以帮助您:
$str="Hi, I'm Gian Marco";
$split=explode("",$str);
$split_rem=array_pop($split);
foreach ($split as $k=>$v)
{
echo $v.'';
}