Stuart Y
Stuart Y

Reputation: 9

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.

Upvotes: 1

Views: 128

Answers (3)

mickmackusa
mickmackusa

Reputation: 47904

It is inefficient and indirect to generate a temporary array to merely cut the first n words from the front of a string. Just use preg_replace() to match and remove n number of non-whitespace sequneces followed by a whitespace character.

Code: (Demo)

$str = 'A big brown fox jumped over the log';

var_export(
    preg_replace('/^(?:\S+\s){3}/', '', $str)
);
// 'fox jumped over the log'

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212412

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

Upvotes: 2

Amal Murali
Amal Murali

Reputation: 76656

echo implode(' ', array_slice(explode(' ', $str), 3));

The output will be fox jumped over the log for all three strings.

Demo!

Upvotes: 1

Related Questions