Louis W
Louis W

Reputation: 3252

preg_split : Get first word in a line

Can you please help assemble a regex to be used in preg_split which will split a string on it's first word - case insensitive (up until the first space).

Upvotes: 0

Views: 2127

Answers (3)

Mansoor Siddiqui
Mansoor Siddiqui

Reputation: 21663

If you just need to split up until the first space character, your regex is essentially just a space character:

$output = preg_split('/ /', 'My name is Mansoor', 2);
echo $output[0]; // Will return 'My';
echo $output[1]; // will return 'name is Mansoor';

If you only need the first word, make sure you pass the optional argument (the 2) to specify that you want only two results in your $output array -- the first word, and the rest of the sentence. Otherwise, you'll spend time parsing text that you don't care about.

Upvotes: 0

codaddict
codaddict

Reputation: 455020

If sentence has space as word separators you can do:

list($firstWord) = explode(' ',trim($input));

Upvotes: 1

Narendra Yadala
Narendra Yadala

Reputation: 9664

This should work

$result = preg_split('/\s/', trim($subject));
$firstword = $result[0]

Upvotes: 1

Related Questions