从字符串的编号列表创建数组


Create Arrays From Numbered List From a String

>我有一个这样的普通字符串:

1 //here is a number defines phrase name
09/25/2013 //here is a date
<i>some text goes here</i> //and goes text
2
09/24/2013 
text goes on and on
4 //as you can see, the numbers can skip another
09/23/2013
heya i'm a text

我需要从中创建数组,但是定义短语的数字必须给我该行的日期,并在我调用它时返回文本。喜欢

$line[4][日期]应该给我"09/23/2013"

这可能吗,如果可能的话,你能解释我怎么做吗?

$stringExample = "1 
09/25/2013 
<i>some text goes here</i> 
2
09/24/2013 
text goes on and on
and on and on
4 
09/23/2013
heya i'm a text";
$data = explode("'r'n'r'n", $stringExample);
$line = array();
foreach ($data as $block) {
    list($id, $date, $text) = explode("'n", $block, 3);
    $index = (int) $id;
    $line[$index] = array();
    $line[$index]["date"] = trim($date);
    $line[$index]["text"] = trim($text);
}

var_dump($line)应输出:

array(3) {
  [1]=>
  array(2) {
    ["date"]=>
    string(10) "09/25/2013"
    ["text"]=>
    string(26) "<i>some text goes here</i>"
  }
  [2]=>
  array(2) {
    ["date"]=>
    string(10) "09/24/2013"
    ["text"]=>
    string(34) "text goes on and on
and on and on"
  }
  [4]=>
  array(2) {
    ["date"]=>
    string(10) "09/23/2013"
    ["text"]=>
    string(15) "heya i'm a text"
  }
}

您可以在此处进行测试。

如果文件的结构是行的共行模式,使用 PHP 您可以读取每一行,每个 1 个都有数字,每个 2 个你有日期,每个 3 个你有文本,每个 4 个你有空,您将计数器重置为 1 并像那样继续,并将值放在数组中, 甚至使用外部索引或第一行(数字)作为索引。

试试这个:

编辑:现在应该适用于多行文本。

//convert the string into an array at newline.
    $str_array = explode("'n", $str);
//remove empty lines.
    foreach ($str_array as $key => $val) {
        if ($val == "") {
            unset($str_array[$key]);
        }
    }
   $str_array = array_values($str_array);

    $parsed_array = array();
    $count = count($str_array);
    $in_block = false;
    $block_num = 0;
    $date_pattern = "%['d]{2}/['d]{2}/['d]{2,4}%";
    for ($i = 0; $i < $count; $i++) {
 //start the block at first numeric value.
        if (isset($str_array[$i])
                && is_numeric(trim($str_array[$i]))) {
// make sure it's followed by a date value
            if (isset($str_array[$i + 1]) 
               && preg_match($date_pattern, trim($str_array[$i + 1]))) {
//number, followed by date, block confirmed.
                $in_block = true;
                $block_num = $i;
                $parsed_array[$str_array[$i]]["date"] = $str_array[$i + 1];
                $parsed_array[$str_array[$i]]['text'] = "";
                $i = $i + 2;
            }
        }
 //once a block has been found, everything that
 //is not "number followed by date" will be appended to the current block's text.
        if ($in_block && isset($str_array[$i])) {
            $parsed_array[$str_array[$block_num]]['text'].=$str_array[$i] . "'n";
        }
    }
    var_dump($parsed_array);