views:

56

answers:

2

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!

+2  A: 
$array=explode("-", "some-string", 1);

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

Brad
Thank you, I just edited my question with more reqs, sorry.
Jimbo
Thanks Brad, this will also be useful. I appreciate your time.
Jimbo
+5  A: 

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

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

staticsan
That is cool. So then I $fixed_string = str_replace("-", " ", $before); to get rid of the - ?
Jimbo
No, the first `-` will be removed as part of the `explode()` function.
staticsan
This worked perfectly for my needs. I was wondering that if I added a $middle then explode - source 3 ?? Would that work or should I use array[x] as mentioned by Brad?
Jimbo
Yes, it does! Thanks so much...
Jimbo