tags:

views:

1376

answers:

5

Hi all,

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!

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

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);
Jacco
Thanks Jacco, this is what I was looking for. +1 for Pascal, as there was some good 'teaching' information in there for me!
Dodinas
This would slightly fail if someone were to use double spacing, I'd probably suggest$result = preg_replace('/^R\s\d+\s/', '', $string, 1);
Mez
A: 
$string = preg_replace('/^R\s+\d+\s*/', '', $string);
too much php
+7  A: 
$string = explode (' ', $string, 3);
$string = $string[2];

Must be much faster than regexes.

Ilya Birman
better than mine
Jacco
Fixed typo in string index in second line (was 3 instead of 2).
Ilya Birman
+3  A: 

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

Pascal MARTIN