从变量中获取特定行

Get a specific line from a variable

如何从包含 10 行或更多行的变量中仅获取特定行? 我试过这段代码:

$line = explode('/n', $lines);

但是现在工作了。

这是我的完整代码:

<?php
$line = explode('\r\n', "i
c");
echo $line[1];
?>

如果您尝试按行拆分,那么您应该使用:

$line = explode("\n", $lines);

举个例子:

<?php

$lines = "first line
second line
third line
fourth line";

$line = explode("\n", $lines);

echo $line[3];

这会给你 fourth line。请记住,数组中的第一个元素是 0,第二个是 1,第三个是 2 等等...

我不确定为什么 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 呈现为两个非白色 space 字符 \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