2013-02-10 44 views
0

例外,新的生产线,我有文字变量:PHP自动阵列与正则表达式

$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 

在此先感谢。

+0

这个变量来自哪里? – 2013-02-10 10:13:18

回答

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 
+0

是的,它的工作,并且qeremy解决方案也工作。多谢你们俩。 – dimsdims 2013-02-10 10:38:34

+0

@dimsdims:不客气。 – Toto 2013-02-10 10:39:23

0
$array = explode("\n", $string); 
foreach($array as $key => $value) { 
    $value = trim($value); 
    if ($value[0] != "[") { 
    echo ($key+1).": $value <br>\n"; 
    } 
} 
+0

有可能与包括“除了这个标题:”回声?显示像我上面的最后一个代码? – dimsdims 2013-02-10 10:09:09

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.bar 
3.cel 
except this title: 
4.one 
5.naa 
+0

也工作过,谢谢。 – dimsdims 2013-02-10 10:34:30

+0

对不起,我点击错误接受答案。但您的解决方案也起作用。 – dimsdims 2013-02-10 10:37:14