Reputation: 12264
I want to split a string into two variables, the first word and the rest of the string. The first word is only ever going to be one of 4 different words.
$string = explode (' ', $string, 2);
$word = $string[0];
$string = $string[1];
The above seems like it works, but I'm wondering if there is a better way.
Upvotes: 3
Views: 2521
Reputation: 48073
In modern PHP, list()
has been replaced by function-less "array destructuring" syntax.
[$word, $string] = explode(' ', $string, 2);
This will populate $word
with the substring that occurs before the first space; the remaining substring (after the first space) will overwrite the original $string
value.
Code: (Demo)
$string = 'This is a test';
[$word, $string] = explode(' ', $string, 2);
var_dump($word, $string);
Output:
string(4) "This"
string(9) "is a test"
Caution: If the input string does not contain a space (e.g. $string = 'This';
), then you'll get:
Warning: Undefined array key 1
string(4) "This"
NULL
Upvotes: 0
Reputation: 817128
You can use list()
:
list($word, $string) = explode (' ', $string, 2);
But it is already fine. Regular expressions would be overkill in this case.
Upvotes: 7
Reputation: 8382
There are many ways you can do it. Using regular expressions, using strtok()
, etc. Using explode()
the way you are doing is quite fine.
Upvotes: 3