Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

split

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!

like image 848
Jimbo Avatar asked Aug 17 '10 23:08

Jimbo


People also ask

How do you split a string on the first occurrence of certain characters?

To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.

How can I split a string into two parts in PHP?

explode() is a built in function in PHP used to split a string in different strings. The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string.

How do I separate comma separated values in PHP?

Use explode() or preg_split() function to split the string in php with given delimiter. PHP | explode() Function: The explode() function is an inbuilt function in PHP which is used to split a string in different strings.

How do you split a string at first in Python?

Use the str. split() method with maxsplit set to 1 to split a string on the first occurrence, e.g. my_str. split('-', 1) .


2 Answers

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

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

like image 169
staticsan Avatar answered Oct 08 '22 20:10

staticsan


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

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

like image 31
Brad Avatar answered Oct 08 '22 20:10

Brad