Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting first two words from string in php [closed]

Tags:

string

php

I have string like:

$message="AB 1234 Hello, how are you?

I want to get like this:

$message[0] = AB
$message[1] = 1234
$message[2] = Hello, how are you?

Please don't suggest substr function because length of first two words may vary but they will have spaces in between. Any other suggestion?

like image 751
fawad Avatar asked Nov 07 '12 05:11

fawad


People also ask

How do I select the first word of a string in PHP?

Method 3: Using strstr() Function: The strstr() function is used to search the first occurrence of a string inside another string. This function is case-sensitive. . strstr ( $sentence , ' ' , true);

What is splitting in PHP?

Definition and Usage. The str_split() function splits a string into an array.

How do I get the first letter of a word in PHP?

So you can easily use $i[0] to fetch first letter.


3 Answers

you can use the following function.

// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

output:
//piece1
//piece2

More information: http://php.net/manual/en/function.explode.php

like image 180
Bhavik Patel Avatar answered Oct 11 '22 12:10

Bhavik Patel


Use explode() with a limit, eg

$message = explode(' ', $message, 3);

If you need more flexibility around the word delimiter, you can do something similar with preg_split()

$message = preg_split('/[\s,]+/', $message, 3)

Demo - http://codepad.org/1gLJEFIa

like image 43
Phil Avatar answered Oct 11 '22 14:10

Phil


If words are simply the first two chunks delimited by sequential whitespace, you could do...

$words = preg_split("/\s+/", $str);

If you want the first two, you could use preg_split()'s limit argument (thanks Phil).

like image 31
alex Avatar answered Oct 11 '22 12:10

alex