如何从 php 字符串中删除第一个单词
我想使用 PHP 删除字符串中的第一个单词。 尝试搜索但找不到我能理解的答案。
例如:“White Tank Top”因此变成“Tank Top”
I'd like to remove the first word from a string using PHP.
Tried searching but couldn't find an answer that I could make sense of.
eg: "White Tank Top" so it becomes "Tank Top"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
不需要爆炸或数组操作,您可以使用函数 strstr:
更新:谢谢到@Sid 要删除多余的空白,您可以执行以下操作:
No need for explode or array manipulation, you can use function strstr:
UPDATE: Thanks to @Sid To remove the extra white space you can do:
您可以将
preg_replace
函数与正则表达式^(\w+\s)
结合使用,该函数将匹配字符串本身的第一个单词:You can use the
preg_replace
function with the regex^(\w+\s)
that will match the first word of a string per se:?
?
确保您选择的方法能够正确处理空字符串、单个单词(不含空格)和多个单词。
我个人会使用
preg_replace()
因为它是最直接的。供您考虑:(演示)
测试和预期结果:
结果:
Make sure that you opt for an approach which will appropriately handle an empty string, a lone word (with no spaces), and multiple words.
I personally would use
preg_replace()
because it is most direct.For your consideration: (Demo)
Tests and expected results:
Outcomes:
Note that
substrStrpos('White')
andexplodeSlice('White')
will both returnWhite
.尝试一下这个功能,希望它对您有用。
Try this function i hope it's work for you .
如果不能保证字符串中包含空格,请小心选择在这种情况下不会失败的技术。
如果使用
explode()
,请务必限制爆炸以获得最佳效率。演示:
输出:
我更喜欢正则表达式技术,因为它在上述所有情况下都是稳定的,并且是单个函数调用。请注意,不需要捕获组,因为全字符串匹配将被替换。
^
匹配字符串的开头,\S+
匹配一个或多个非空白字符,\s
匹配一个空白字符。If you are not guaranteed to have a space in your string, be careful to choose a technique that won't fail on such cases.
If using
explode()
be sure to limit the explosions for best efficiency.Demonstration:
Output:
My preference is the regex technique because it is stable in all cases above and is a single function call. Note that there is no need for a capture group because the fullstring match is being replaced.
^
matches the start of the string,\S+
matches one or more non-whitespace characters and\s
matches one whitespace character.