如何使用 PHP 在第一次出现“-”(减号)时将字符串拆分为两个 $vars?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3507901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:02:12  来源:igfitidea点击:

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

phpsplit

提问by Jimbo

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

如何使用 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!

在此先感谢您的帮助!

回答by staticsan

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

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

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

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

回答by Brad

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

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

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

回答by Oleg

You can use strtokfunction:

您可以使用strtok函数:

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

回答by Murat Tutumlu

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

这是您需要的:使用 list() 和 expand():

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

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

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