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

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

I found how to divide into each "-", but not just the first occurrence.

Example:

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

Notice also the first "-" is stripped.

Thanks in advance for your help!

+42
split php
Aug 17 '10 at 23:55
source share
4 answers

It is very simple, using the optional explode parameter, which many people do not understand:

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

+98
Aug 17 '10 at 23:56
source share
 $array = explode('-', 'some-string', 2); 

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

+26
Aug 17 '10 at 23:56
source share

You can use strtok :

 $first = strtok($string, '-'); 
+1
Nov 13 '17 at 22:16
source share

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 (-)

0
Aug 07 '17 at 2:43 on
source share



All Articles