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?
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);
Definition and Usage. The str_split() function splits a string into an array.
So you can easily use $i[0] to fetch first letter.
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
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With