0

我在变量中有文本:

$string = "foo
    bar
    cel
    [except this title:]
    one
    naa
";

我需要将它转换为数组但排除“[除了这个标题:]”:

Array
        (
            [0] => foo
            [1] => bar
            [2] => cel
            [3] => one
            [4] => naa
        )

我试过这个代码:

$string = "foo
    bar
    [except this title:]
    cel
    one
    naa";
$array = preg_split("/(\r\n|\n|\r)/", $string);
$i = 1;
foreach($array as $key => $value) {
  echo "$i: $value <br>";
  $i++;
}

但显示:

1: foo
2: bar
3: [except this title:]
4: cel
5: one
6: naa 

我想要这样的显示代码:

1.foo
2.bar

except this title:
3.cel
4.one
5.naa

提前致谢。

4

3 回答 3

0

怎么样:

$string = "foo
    bar
    [except this title:]
    cel
    one
    naa";
$array = preg_split("/[\r\n]+/", $string);
$i = 1;
foreach($array as $key => $value) {
  $value = trim($value);
    if ($value[0] == '[') {
        $value = preg_replace('/[[\]]/', '', $value);
        echo "<br>$value<br>";
    } else {
        echo "$i.$value<br>";
        $i++;
    }
}

输出:

1.foo
2.bar

except this title:
3.cel
4.one
5.naa
于 2013-02-10T10:31:12.003 回答
0
$a = preg_split("~[\n]+\s*~", $string, -1, PREG_SPLIT_NO_EMPTY);
$i = 0;
foreach ($a as $v) {
    $v = trim($v);
    if ($v[0] == "[") {
        echo trim($v, "\x5b..\x5d") ."\n";
        continue;
    }
    echo (++$i) .".$v\n";
}

出去;

1.foo
2.酒吧
3.cel
除了这个标题:
4.一个
5.naa
于 2013-02-10T10:31:21.200 回答
0
$array  = explode("\n", $string);
foreach($array as $key => $value) {
  $value = trim($value);
  if ($value[0] != "[") {
    echo ($key+1).": $value <br>\n";
  }
}
于 2013-02-10T10:02:09.553 回答