简体   繁体   English

从字符串中删除前两个单词

[英]Remove first two words from a string

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" (eg, the initial "R" and then the subsequent numbers)? 使用PHP,删除前两个“单词”(例如,初始“R”然后是后续数字)的最佳方法是什么?

Thanks for the help! 谢谢您的帮助!

$string = explode (' ', $string, 3);
$string = $string[2];

Must be much faster than regexes. 必须比正则表达式快得多。

try 尝试

$result = preg_replace('/^R \\d+ /', '', $string, 1);

or (if you want your spaces to be written in a more visible style) 或(如果您希望以更明显的方式书写空格)

$result = preg_replace('/^R\\x20\\d+\\x20/', '', $string, 1);

One way would be to explode the string in "words", using explode or preg_split (depending on the complexity of the words separators : are they always one space ? ) 一种方法是使用explodepreg_splitexplode “单词”中的字符串(取决于单词分隔符的复杂性:它们总是一个空格吗?)

For instance : 例如 :

$string = "R 124 This is my message";
$words = explode(' ', $string);
var_dump($words);

You'd get an array like this one : 你会得到一个像这样的数组:

array
  0 => string 'R' (length=1)
  1 => string '124' (length=3)
  2 => string 'This' (length=4)
  3 => string 'is' (length=2)
  4 => string 'my' (length=2)
  5 => string 'message' (length=7)

Then, with array_slice , you keep only the words you want (not the first two ones) : 然后,使用array_slice ,您只保留您想要的单词(而不是前两个单词):

$to_keep = array_slice($words, 2);
var_dump($to_keep);

Which gives : 这使 :

array
  0 => string 'This' (length=4)
  1 => string 'is' (length=2)
  2 => string 'my' (length=2)
  3 => string 'message' (length=7)

And, finally, you put the pieces together : 最后,你把各个部分组合在一起:

$final_string = implode(' ', $to_keep);
var_dump($final_string);

Which gives... 这使...

string 'This is my message' (length=18)

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/or preg_split ^^ 实际上,这就是为什么你可以选择那个解决方案的原因,这个解决方案比仅使用explode和/或preg_split更长一点^^

$string = preg_replace("/^\\w+\\s\\d+\\s(.*)/", '$1', $string);
$string = preg_replace('/^R\s+\d+\s*/', '', $string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM