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

时间:2013-09-26 17:05:34

标签: php

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

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] [date]应该给我“09/23/2013”​​

这有可能,如果可能,你可以解释一下如何做到这一点吗?

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

$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"
  }
}

您可以对其进行测试here

答案 2 :(得分:0)

试试这个:

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

//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);