php自动数组新行,正则表达式除外
我在变量中有文本:php自动数组新行,正则表达式除外,php,regex,arrays,Php,Regex,Arrays,我在变量中有文本: $string = "foo bar cel [except this title:] one naa "; 我需要将其转换为数组,但不包括“[除此标题:]”: 我尝试了以下代码: $string = "foo bar [except this title:] cel one naa"; $array = preg_split("/(\r\n|\n|\r)/", $string); $i = 1
$string = "foo
bar
cel
[except this title:]
one
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
except this title:
3.cel
4.one
5.naa
1.foo
2.bar
except this title:
3.cel
4.one
5.naa
提前感谢。$array=explode(“\n”,$string);
$array = explode("\n", $string);
foreach($array as $key => $value) {
$value = trim($value);
if ($value[0] != "[") {
echo ($key+1).": $value <br>\n";
}
}
foreach($key=>$value的数组){
$value=修剪($value);
如果($value[0]!=“[”){
echo($key+1)。“:$value\n”; } } 那么:
$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.2巴
3.cel
除本标题外:
4.1
5.naa
可以使用include“除此标题外:”?像上面我的最后一个代码一样显示?。此变量来自何处?很抱歉,我单击了错误的接受答案。但您的解决方案也起了作用。是的,它起了作用,qeremy解决方案也起了作用。谢谢你们两位。
$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
$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