我想使用PHP从一个字符串中删除第一个单词。尝试搜索但找不到让我能够理解的答案。
例如:"白色背心",变成 "背心"。
谢谢
我想使用PHP从一个字符串中删除第一个单词。尝试搜索但找不到让我能够理解的答案。
例如:"白色背心",变成 "背心"。
谢谢
不需要使用explode或数组操作,你可以使用函数strstr:
echo strstr("White Tank Top"," ");
//Tank Top
更新:感谢 @Sid 提供的解答,为了去除额外的空格,您可以执行以下操作:
echo substr(strstr("White Tank Top"," "), 1);
strtr
。本来要用 strpos
+ substr
打出 3 行代码,但看到你的答案后就不用了。加上 ltrim
以防有多个空格,就万事大吉了。 - Fanis Hatzidakisstrlen
或在调试器中运行它,然后您就能发现它 :) - Fanis Hatzidakisstrlen
函数显示了空格的有趣之处,感谢你们提供的解决方案! - amosriverapreg_replace
函数,并使用正则表达式 ^(\w+\s)
匹配字符串的第一个单词:$str = "White Tank Top";
$str = preg_replace("/^(\w+\s)/", "", $str);
var_dump($str); // -> string(8) "Tank Top"
function remove_word($sentence)
{
$words=array_shift(explode(' ', $sentence));
return implode(' ', $words);
}
?
return implode(' ', array_shift(explode(' ', $sentence)));
吗?我对PHP从来不是很确定。 - Patrick Perinifunction remove_word($sentence)
{
$exp = explode(' ', $sentence);
$removed_words = array_shift($exp);
if(count($exp)>1){
$w = implode(' ', $exp);
}else{
$w = $exp[0];
}
return $w;
}
$string = 'White Tank Top';
$split = explode(' ', $string);
if (count($split) === 1) {
// do you still want to drop the first word even if string only contains 1 word?
// also string might be empty
} else {
// remove first word
unset($split[0]);
print(implode(' ', $split));
}
如果您的字符串中不能保证有空格,请小心选择不会在这种情况下失败的技术。
如果使用explode()
,请确保限制爆炸以获得最佳效率。
演示:
$strings = ["White", "White Tank", "White Tank Top"];
foreach ($strings as $string) {
echo "\n{$string}:";
echo "\n-\t" , substr($string, 1 + (strpos($string, ' ') ?: -1));
$explodeOnce = explode(' ', $string, 2);
echo "\n-\t" , end($explodeOnce);
echo "\n-\t" , substr(strstr($string, " "), 1);
echo "\n-\t" , ltrim(strstr($string, " "));
echo "\n-\t" , preg_replace('~^\S+\s~', '', $string);
}
输出:
White:
- White
- White
- // strstr() returned false
- // strstr() returned false
- White
White Tank:
- Tank
- Tank
- Tank
- Tank
- Tank
White Tank Top:
- Tank Top
- Tank Top
- Tank Top
- Tank Top
- Tank Top
我更喜欢使用正则表达式技术,因为它在所有情况下都很稳定,并且只需要一个函数调用。请注意,不需要捕获组,因为正在替换的是完整字符串匹配。 ^
匹配字符串的开头,\S+
匹配一个或多个非空白字符,\s
匹配一个空格字符。