Reputation: 4705
Say I have the following: 44-xkIolspO
I want to return 2 variables:
$one = "44";
$two = "xkIolspO";
What would be the best way to do this?
Upvotes: 18
Views: 27648
Reputation: 48011
There are a number of native, single-function solutions to split on your delimiting character. Demo
sscanf()
offers two styles of implementation -- reference variables as trailing parameters or if there are no references it will return the captures as an array. The power is in the placeholders -- %d
will return the leading number from the sample input as an integer-type value. Recommended if your string is predictably formatted.
sscanf($text, '%d-%s', $one, $two);
or destructure the return:
[$one, $two] = sscanf($text, '%d-%s');
explode()
is the most commonly used tool for this task and certainly reliable for thus task. Its return value will need to be destructured as individual variables.
[$one, $two] = explode('-', $text);
str_getcsv()
can be modified to split on hyphens instead of commas. While this approach works on the sample string, this function provides some magic behaviors regarding escaping which may not be desirable for general-use. Not recommended.
[$one, $two] = str_getcsv($text, '-');
preg_split()
will work just like explode()
if fed the literal hyphen in a regular expression, but less efficiently than all other mentioned techniques. It has helpful behavior modifying flags but none which are helpful for this task. Not recommended.
[$one, $two] = preg_split('/-/', $text);
Upvotes: 1
Reputation: 103145
PHP has a function called preg_split() splits a string using a regular expression. This should do what you want.
Or explode() might be easier.
$str = "44-xkIolspO";
$parts = explode("-", $str);
$one = $parts[0];
$two = $parts[1];
Upvotes: 11
Reputation: 82933
Try this:
list($one, $two) = split("-", "44-xkIolspO", 2);
list($one, $two) = explode("-", "44-xkIolspO", 2);
Upvotes: 44