如何在第一次出现“-”(负号)时将字符串分割成两个$vars ?

时间:2022-10-14 21:43:27

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

如何在第一次出现-(负号)时将字符串分割成两个$vars ?

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!

谢谢你的帮助!

4 个解决方案

#1


107  

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

这很简单,用一个额外的参数引爆,很多人都没有意识到:

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

列表($before, $after) =爆炸('-',$source, 2);

#2


31  

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

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

然后你可以做$var1=$array[0]和$var2[1]。

#3


1  

You can use strtok function:

可以使用strtok函数:

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

#4


0  

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

下面是您需要的:使用list() with explosion ():

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

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

注意“-”(负号)周围的空格

#1


107  

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

这很简单,用一个额外的参数引爆,很多人都没有意识到:

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

列表($before, $after) =爆炸('-',$source, 2);

#2


31  

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

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

然后你可以做$var1=$array[0]和$var2[1]。

#3


1  

You can use strtok function:

可以使用strtok函数:

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

#4


0  

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

下面是您需要的:使用list() with explosion ():

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

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

注意“-”(负号)周围的空格