如何在第一个冒号处拆分字符串

时间:2023-01-18 21:42:28
$str = "X-Storage-Url: https://pathofanapi";

I would like to split this into an array ("X-Storage-Url", "https://pathofanapi").

我想将其拆分为一个数组(“X-Storage-Url”,“https:// pathofanapi”)。

Could someone tell me the regex for this ? Regex has always been my weakness.

有人可以告诉我这个正则表达式吗?正则表达式一直是我的弱点。

Thanks.

谢谢。

2 个解决方案

#1


3  

$array = array_map('trim', explode(':', $str, 2));

#2


0  

As it's been said, explode is the right tool to do this job.

正如人们所说,爆炸是完成这项工作的正确工具。

However, if you really want a regex, here is a way to do:

但是,如果你真的想要一个正则表达式,这是一种方法:

with preg_match:

与preg_match:

$str = "X-Storage-Url: https://pathofanapi";
preg_match('/^([^:]+):\s*(.*)$/', $str, $m);
print_r($m);

output:

输出:

Array
(
    [0] => X-Storage-Url: https://pathofanapi
    [1] => X-Storage-Url
    [2] => https://pathofanapi
)

or with preg_split;

或者使用preg_split;

$arr = preg_split('/:\s*/', $str, 2);
print_r($arr);

output:

输出:

Array
(
    [0] => X-Storage-Url
    [1] => https://pathofanapi
)

#1


3  

$array = array_map('trim', explode(':', $str, 2));

#2


0  

As it's been said, explode is the right tool to do this job.

正如人们所说,爆炸是完成这项工作的正确工具。

However, if you really want a regex, here is a way to do:

但是,如果你真的想要一个正则表达式,这是一种方法:

with preg_match:

与preg_match:

$str = "X-Storage-Url: https://pathofanapi";
preg_match('/^([^:]+):\s*(.*)$/', $str, $m);
print_r($m);

output:

输出:

Array
(
    [0] => X-Storage-Url: https://pathofanapi
    [1] => X-Storage-Url
    [2] => https://pathofanapi
)

or with preg_split;

或者使用preg_split;

$arr = preg_split('/:\s*/', $str, 2);
print_r($arr);

output:

输出:

Array
(
    [0] => X-Storage-Url
    [1] => https://pathofanapi
)