Reputation: 3252
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
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
Reputation: 455020
If sentence has space as word separators you can do:
list($firstWord) = explode(' ',trim($input));
Upvotes: 1
Reputation: 9664
This should work
$result = preg_split('/\s/', trim($subject));
$firstword = $result[0]
Upvotes: 1