Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first two words from a string

Tags:

php

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!

like image 898
Dodinas Avatar asked Nov 28 '22 23:11

Dodinas


2 Answers

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

Must be much faster than regexes.

like image 140
Ilya Birman Avatar answered Dec 10 '22 08:12

Ilya Birman


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

like image 42
Pascal MARTIN Avatar answered Dec 10 '22 07:12

Pascal MARTIN