phpstringsubstringcpu-wordtruncation

Remove first n words from string


I'm wanting to remove the first three items from a string, but the problem is I can't use substr() because I don't know how many characters each word may contain since the data is coming from UI

ie;

$str = A big brown fox jumped over the log;
//$str = A slow red fox jumped over the log;
//$str = An enthusiastic brown fox jumped over the log;

I'd like to remove the first three words (including spaces) so the new string starts with "fox" then I plan on storing this data in a new variable.

I'm hoping there's an easier way than exploding this and removing 0,1 and 2 from the array all of which I am unfamiliar with and if anyone knows how to one line this I'd be most appreciative if you'd share with me.


Solution

  • Assuming a simple split on space to differentiate words

    $str = 'A big brown fox jumped over the log';
    $rest = preg_split('/ /',$str, 4)[3];
    

    Modify the regexp if you want to adjust for punctuation marks as well

    If you're on a version of PHP that doesn't support array dereferencing:

    $str = 'A big brown fox jumped over the log';
    $split = preg_split('/ /',$str, 4);
    $rest = $split[3];