How can I split a string at the first occurrence of "-" (minus sign) into two $vars with PHP?

PhpSplit

Php Problem Overview


How can I split a string at the first occurrence of - (minus sign) into two $vars with PHP?

I have found how to split on every "-" but, not only on the first occurrence.

example:

this - is - line - of whatever - is - relevant
$var1 = this
$var2 = is - line - of whatever - is - relevant

Note, also stripped the first "-" .

Thanks in advance for the help!

Php Solutions


Solution 1 - Php

It's very simple, using an extra paramater to explode that many people don't realize is there:

list($before, $after) = explode('-', $source, 2);

Solution 2 - Php

$array = explode('-', 'some-string', 2);

Then you could do $var1=$array[0] and $var2=$array[1].

Solution 3 - Php

Here is what you need: using list() with explode():

list($var1, $var2) = explode(' - ', 'this - is - line - of whatever - is - relevant', 2);

Note the spaces around the "-" (minus sign)

Solution 4 - Php

You can use strtok function:

$first = strtok($string, '-');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJimboView Question on Stackoverflow
Solution 1 - PhpstaticsanView Answer on Stackoverflow
Solution 2 - PhpBradView Answer on Stackoverflow
Solution 3 - PhpMurat TutumluView Answer on Stackoverflow
Solution 4 - PhpOlegView Answer on Stackoverflow