我有一套绳子
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";得到那根绳子最好的方法是什么?我应该先使用",",然后再使用":",还是有一种解决方案?
提前谢谢你。
发布于 2013-09-06 22:57:20
就像这样:
$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
)发布于 2013-09-06 22:54:09
我将在字符串上使用一个简单的爆发,然后为每个元素填充一个包含键/值信息的数组:
$string = 'Host: ...';
$raw_array = explode(',', $string);
$final_array = array();
foreach($raw_array as $item) {
$item_array = explode(':', trim($item));
$key = trim($item_array[0]);
$value = trim($item_array[1]);
$final_array[$key] = $value;
}
var_dump($final_array);请注意,这不是像在问题中所问的那样使用单个变量,而是使用基于字符串键的键值填充单个数组。这是一种更灵活的办法。
发布于 2013-09-06 23:04:03
您可以使用regex替换将其转换为查询字符串-esq字符串,然后使用parse_str将其转换为关联数组。没有循环,两条线!
$string = preg_replace(array('/:/', '/, /'), array('=','&'), $string);
parse_str($string, $output);
var_dump($output);
/*
array(8) { ["Host"]=> string(8) " xxx.com" ["IP_address"]=> string(13) " 37.0.122.151" ["SBL"]=> string(10) " SBL196170" ["status"]=> string(8) " unknown" ["level"]=> string(2) " 4" ["Malware"]=> string(8) " Citadel" ["AS"]=> string(7) " 198310" ["country"]=> string(3) " RU" }
*/在这里试试:http://codepad.viper-7.com/5gwWyC
文档
preg_replace - http://php.net/manual/en/function.preg-replace.phpparse_str - http://php.net/manual/en/function.parse-str.phphttps://stackoverflow.com/questions/18667701
复制相似问题