Simple way to get first word of a string
How do i get first 开发者_StackOverflowword of a string in var1 and rest in 2nd var.
My Requirement:
$strInput = "SSCL BAl 101";
$strFirst = ...;
$strRest = ...;
My Output:
strFirst = SSCL
strRest = BAL 101
My Current Solution:
list($strFirst,) = explode(" ", $strInput );
$strRest = trim(str_replace($strFirst, '', $strInput ));
Is there any other simple way too?
Don't know php too well, but looks like you could always call strstr()
twice (if you're using php >= 5.3.0). http://www.php.net/manual/en/function.strstr.php
$first = strstr($strInput, ' ', true);
$rest = strstr($strInput, ' ');
Use the limit for the explode():
list($strFirst,$strRest) = explode(" ", trim($strInput), 2);
I don't know about optimization, but it is one line and rather readable. You could do it with a regex if you like:
list($strFirst,$strRest) = preg_split("/ /", trim($strInput), 2); // PHP >= 5.3 I believe
EDIT
Added the trim for leading whitespace fail!
$strInput = "SSCL BAl 101";
$strFirst = strtok($strInput, ' ');
$strRest = substr($strInput, strlen($strFirst));
var_dump($strFirst, $strRest);
Output
string(4) "SSCL"
string(8) " BAl 101"
CodePad.
精彩评论