在PHP中将一系列字符串解析为数组的数组

时间:2013-02-02 20:19:11

标签: php arrays string forms parsing

刚接触PHP并查看了文档等等,我无法找到这个问题的答案。

我想接受$_POST输入,例如:

Large Automated Structural Restoration  1   Hull Repair Unit        Medium  50 m3
Experimental 10MN Microwarpdrive I  5   Propulsion Module       Medium  50 m3
Warp Disruptor I    1   Warp Scrambler      Medium  5 m3
Upgraded EM Ward Amplifier I    1   Shield Amplifier        Medium  5 m3
Tracking Disruptor I    1   Tracking Disruptor  Small   Medium  5 m3

进入array之类:

[Experimental 10MN Microwarpdrive I] [5] [Propulsion Module] [] [Medium] [50] //Disregard m3
[Warp Disruptor I] [1] [Warp Scrambler] [] [Medium] [5]
...
[Tracking Disruptor I] [1] [Tracking Disruptor] [Small] [Medium] [5]

我可以调用像$asset[0][name]这样的变量,这样我就可以准备一个XML调用外部资源了。

逻辑正在逃避我或我不理解某事。请帮忙!

2 个答案:

答案 0 :(得分:1)

$aero=explode(PHP_EOL,trim($_POST['textarea'])); //separate each line
$asset=array(); //init the assets
foreach ($aero as $unit) { //loop each line
    $detail=explode("\t",$unit); //split by tab
    $name=$detail[0]; //assign the name to the first item in the arr
    unset($detail[count($detail)-1]); //delete the last item ('m3' not needed)
    unset($detail[0]); //delete the first item (we saved it as $name)
    $asset[][$name]=$detail; //add an array item
}

只是为了好玩,这是另一种使用正则表达式1-liner的解决方案,当你没有标签时:

$regex='/^([A-Za-z0-9 ]+) (\d+) ([A-Z][A-Za-z ]+?)(\ ()|\ (Small)\ )([A-Z][a-z]+) (\d+) m3$/m';
preg_match_all($regex,$textarea,$aero);
$asset=array();    
foreach ($aero[1] as $no=>$unit) {
    $asset[$unit]=array($aero[2][$no],
                $aero[3][$no], 
                $aero[6][$no], 
                $aero[7][$no], 
                $aero[8][$no]); 
}

这个位可能需要一点点添加:(\ ()|\ (Small)\ ) (\ ()|\ (Small)\ |\ (Medium)\ |\ (Large)\ )

处理前示例中第一行和最后一行的正则表达式输出:

Array ( [0] => Array ( [0] => Large Automated Structural Restoration 1 Hull Repair Unit Medium 50 m3 [1] => Tracking Disruptor I 1 Tracking Disruptor Small Medium 5 m3 )  
[1] => Array ( [0] => Large Automated Structural Restoration [1] => Tracking Disruptor I )  
[2] => Array ( [0] => 1 [1] => 1 )  
[3] => Array ( [0] => Hull Repair Unit [1] => Tracking Disruptor )  
[4] => Array ( [0] => [1] => Small )  
[5] => Array ( [0] => [1] => )  
[6] => Array ( [0] => [1] => Small )  
[7] => Array ( [0] => Medium [1] => Medium )  
[8] => Array ( [0] => 50 [1] => 5 ) )

答案 1 :(得分:0)

如果你explode字符串的正则表达式为> 1空格,那么一切都在一个你可以做你想做的数组中。

$reg = '\s+';
$ar = explode($reg,$_POST['val']);
相关问题