我不确定为什么 explode 对你不起作用(它应该)。我会建议 PHP_EOL 作为分隔符,看看它是如何吸引你的。为了比较,您可以使用preg_match(),但这会更慢。
代码:(Demo)
$string='line1
line2
line3 line 3
line4
line five
line 6
line 7
line eight
line 9
line 10
line eleven';
for($x=1; $x<10; $x+=2){ // $x is the targeted line number
echo "$x preg_match: ";
echo preg_match('/(?:^.*$\R?){'.($x-1).'}\K.*/m',$string,$out)?$out[0]:'fail';
echo "\n explode: ";
echo explode(PHP_EOL,$string)[$x-1];
echo "\n---\n";
}
输出
1 preg_match: line1
explode: line1
---
3 preg_match: line3 line 3
explode: line3 line 3
---
5 preg_match: line five
explode: line five
---
7 preg_match: line 7
explode: line 7
---
9 preg_match: line 9
explode: line 9
---
我想得越多,您的报价可能就有问题。单引号将\n 呈现为两个非空白字符\ 和n。您必须使用双引号将其视为换行符。
Another demo:
echo 'PHP_EOL ',explode(PHP_EOL,$string)[0]; // PHP_EOL works
echo "\n\n",'"\\n" ',explode("\n",$string)[0]; // "\n" works
echo "\n\n","'\\n' ",explode('\n',$string)[0]; // '\n' doesn't work, the newline character is "literally" interpreted as "backslash n"
输出:
PHP_EOL line1 // This is correct
"\n" line1 // This is correct
'\n' line1 // The whole string is printed because there is no "backslash n" to explode on.
line2
line3 line 3
line4
line five
line 6
line 7
line eight
line 9
line 10
line eleven