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)?
Thanks for the help!
$string = explode (' ', $string, 3);
$string = $string[2];
Must be much faster than regexes.
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 ? )
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) :
$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
^^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With