简体   繁体   中英

How to split a string at the first colon

$str = "X-Storage-Url: https://pathofanapi";

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

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

Thanks.

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

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:

$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;

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

output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM