微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 分割字符串的最佳方法是什么

我有这个字符串集

Host: example.com, IP address: 37.0.122.151, SBL: SBL196170, status: unkNown, level: 4, Malware: Citadel, AS: 198310, country: RU

我想以这种格式提供每个数据.

$host = "example.com";
$ip = "37.0.122.151";
$SBL = "SBL196170";
$status = unkNown;
$level = "4";
$malware = "Citadel";
$as = "1098310";
$country = "RU";

获得该字符串的最佳方法是什么?我应该首先用“,”分开,然后用“:”分开,还是有一个分裂的解决方案?

先感谢您.

解决方法:

像这样:

$input = "Host: example.com, IP address: 37.0.122.151, SBL: SBL196170, status: unkNown, level: 4, Malware: Citadel, AS: 198310, country: RU";
preg_match_all('/(\w+): ([\w.]+)/', $input, $matches);
print_r($matches);

输出

Array
(
    [0] => Array
        (
            [0] => Host: example.com
            [1] => address: 37.0.122.151
            [2] => SBL: SBL196170
            [3] => status: unkNown
            [4] => level: 4
            [5] => Malware: Citadel
            [6] => AS: 198310
            [7] => country: RU
        )

    [1] => Array
        (
            [0] => Host
            [1] => address
            [2] => SBL
            [3] => status
            [4] => level
            [5] => Malware
            [6] => AS
            [7] => country
        )

    [2] => Array
        (
            [0] => example.com
            [1] => 37.0.122.151
            [2] => SBL196170
            [3] => unkNown
            [4] => 4
            [5] => Citadel
            [6] => 198310
            [7] => RU
        )

)

然后:

$mydata = array_combine($matches[1], $matches[2]);
print_r($mydata);

得到:

Array
(
    [Host] => example.com
    [address] => 37.0.122.151
    [SBL] => SBL196170
    [status] => unkNown
    [level] => 4
    [Malware] => Citadel
    [AS] => 198310
    [country] => RU
)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐