4

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

5 Answers 5

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

Must be much faster than regexes.

Sign up to request clarification or add additional context in comments.

1 Comment

Fixed typo in string index in second line (was 3 instead of 2).
6

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

Comments

5

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

2 Comments

Thanks Jacco, this is what I was looking for. +1 for Pascal, as there was some good 'teaching' information in there for me!
This would slightly fail if someone were to use double spacing, I'd probably suggest $result = preg_replace('/^R\s\d+\s/', '', $string, 1);
0
$string = preg_replace("/^\\w+\\s\\d+\\s(.*)/", '$1', $string);

Comments

0
$string = preg_replace('/^R\s+\d+\s*/', '', $string);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.