从字符串中删除前两个单词
我有一个字符串:
$string = "R 124 This is my message";
有时,该字符串可能会发生变化,例如:
$string = "R 1345255 This is another message";
使用 PHP,删除前两个“单词”(例如,最初的“R”,然后是后续数字)的最佳方法是什么?
I have a string:
$string = "R 124 This is my message";
At times, the string may change, such as:
$string = "R 1345255 This is another message";
Using PHP, what's the best way to remove the first two "words" (e.g., the initial "R" and then the subsequent numbers)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一定比正则表达式快得多。
Must be much faster than regexes.
一种方法是使用
explode
或preg_split
(取决于单词分隔符的复杂性:它们总是一个空格吗? )例如:
你会得到一个像这样的数组:
然后,使用
array_slice
,你只保留你想要的单词(而不是前两个):这给出了:
最后,你将各个部分放在一起:
这给出了......
并且,如果有必要,它允许你做几个在将单词重新组合在一起之前对单词进行处理:-)
实际上,这就是您可能选择该解决方案的原因,该解决方案比仅使用
explode
和/或preg_split
^^One way would be to explode the string in "words", using
explode
orpreg_split
(depending on the complexity of the words separators : are they always one space ? )For instance :
You'd get an array like this one :
Then, with
array_slice
, you keep only the words you want (not the first two ones) :Which gives :
And, finally, you put the pieces together :
Which gives...
And, if necessary, it allows you to do couple of manipulations on the words before joining them back together :-)
Actually, this is the reason why you might choose that solution, which is a bit longer that using only
explode
and/orpreg_split
^^尝试
或(如果您希望您的空间以更明显的风格书写)
try
or (if you want your spaces to be written in a more visible style)