Fetching the first word of a string using php

I want to split a string into two variables, the first word and the rest of the string. The first word will be only one of four different words.

$string = explode (' ', $string, 2);
$word = $string[0];
$string = $string[1];

The above seems to work, but I wonder if there is a better way.

+3
source share
3 answers

You can use list():

list($word, $string) = explode (' ', $string, 2);

But this is already good. In this case, regular expressions will be redundant.

+6
source

There are many ways to do this. Using regular expressions, using strtok()etc. Using explode()how you do is good.

+3
source
list($word, $string) = explode(' ', $a, 2);
+1
source

Source: https://habr.com/ru/post/1752133/


All Articles