PHP将格式化文本分解为数组

时间:2014-02-24 21:50:31

标签: php

我正在尝试从PHP中解析的http://shoelace.io/获取一些Jade格式的布局格式 我有这个格式化的文本

.row.rowname
  .boxname.col-sm-4
  .boxtwo.col-sm-4
  .boxthree.col-sm-4
.row.therowbelowhasnoname
  .theboxbelowhasnoname.col-sm-8
  .col-sm-4
.row
  .col-sm-4
  .col-sm-8

我想爆炸成多维数组 像这样的东西。

Array
(
    [rowname] => Array
        (
            [col] => Array
                (
                    [coltype] => col-sm-4
                    [colname] => boxname
                )

            [col] => Array
                (
                    [coltype] => col-sm-4
                    [colname] => boxtwo
                )
        )
    [therowbelowhasnoname] => Array
        (
            [col] => Array
                (
                    [coltype] => col-sm-8
                    [colname] => theboxbelowhasnoname
                )

            [col] => Array
                (
                    [coltype] => col-sm-4
                    [colname] => boxtwo
                )
        )
)

我将如何解决这个问题。 如果我只用新行('\ n')爆炸,我会失去col的

的双倍空格

2 个答案:

答案 0 :(得分:2)

我不确定你在[col]中想要什么,但我把它变成了数组

$string = ".row.rowname
  .boxname.col-sm-4
  .boxtwo.col-sm-4
  .boxthree.col-sm-4
.row.therowbelowhasnoname
  .theboxbelowhasnoname.col-sm-8
  .col-sm-4
.row
  .col-sm-4
  .col-sm-8";

$array = array();
$lastindex = null;
$continueuntillfound = null;
foreach(explode(PHP_EOL,$string) as $item)
{
  if($continueuntillfound and $item != $continueuntillfound)
    continue;
  $continueuntillfound = null;
  if($item == '.row')
  {
    $continueuntillfound = '.row.';
    continue;
  }
  elseif(strpos($item,'.row.') === 0)
  {
    $lastindex = substr($item,5);
    $array[$lastindex] = array();
  }
  elseif($lastindex and $explode = explode('.',$item) and count($explode) > 2)
  {
    $array[$lastindex][] = array('coltype' => $explode[2],'colname' => $explode[1]);
  }
  elseif($explode = explode('.',$item))
  {
    $array[$lastindex][] = array('coltype' => $explode[1],'colname' => 'boxtwo');
  }
}

print_r($array);

答案 1 :(得分:0)

在你的情况下,我会尝试找到一个玉石解析器而不是自己构建。

现在,如果你仍然想要自己尝试,第一步是使用\ n.row preg_split文本(这意味着文本.row前面有一个新行)。我还会在开始时添加一个空行,以便捕获第一个.row

$text=".row.rowname
  .boxname.col-sm-4
  .boxtwo.col-sm-4
  .boxthree.col-sm-4
.row.therowbelowhasnoname
  .theboxbelowhasnoname.col-sm-8
  .col-sm-4
.row
  .col-sm-4
  .col-sm-8";



$tarray=preg_split("/\n\.row/","\n".$text,-1,PREG_SPLIT_NO_EMPTY);
var_dump($tarray);