2

作为 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

变成一个arraylike:

[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 调用。

逻辑正在逃避我,或者我不理解某些东西。请帮忙!

4

2 回答 2

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 ) )
于 2013-02-02T20:57:36.950 回答
0

如果您explode的字符串的正则表达式分隔符为 >1 个空格,那么所有内容都将位于一个数组中,您可以使用该数组执行您想要的操作。

$reg = '\s+';
$ar = explode($reg,$_POST['val']);
于 2013-02-02T20:26:26.843 回答