Remove the first two words from the string

I have a line:

$string = "R 124 This is my message"; 

Sometimes the string may change, for example:

 $string = "R 1345255 This is another message"; 

Using PHP, the best way to remove the first two words (for example, the initial "R" and then the subsequent numbers)?

Thanks for the help!

+4
source share
5 answers

to try

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

or (if you want your spaces to be written in a more understandable style)

 $result = preg_replace('/^R\\x20\\d+\\x20/', '', $string, 1); 
+5
source
 $string = explode (' ', $string, 3); $string = $string[2]; 

It should be much faster than regular expressions.

+15
source

One way is to blow up a line in words using explode or preg_split (depending on the complexity of word separators: are they always the same space?)

For instance:

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

You will get an array like this:

 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, array_slice , you save only the words you need (not the first two):

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

What 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 add the fragments:

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

What gives...

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

And, if necessary, this allows you to do a couple of manipulations on words before attaching them back together :-) Actually, this is the reason you can choose a solution that is a little longer using only explode and / or preg_split ^ ^

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

All Articles