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!

Was it helpful?



$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);


$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);

You'd get an array like this one :

  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);

Which gives :

  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);

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 ^^

$string = preg_replace("/^\\w+\\s\\d+\\s(.*)/", '$1', $string);
$string = preg_replace('/^R\s+\d+\s*/', '', $string);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow