0

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

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”

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

4

3 回答 3

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

你可以在这里测试它。

于 2013-09-26T17:16:53.230 回答
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);
于 2013-09-26T17:27:00.963 回答
0

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

于 2013-09-26T17:11:13.067 回答