如何从包含10行或更多行的变量中仅获取特定行? 我试过这段代码:
tasks:
- name: Copy bulk files
copy:
src: "{{ item }}"
dest: /ansible/sri
with_fileglob: "/tmp/guru/{{ copy }}*"
但现在正在工作。
这是我的完整代码:
$line = explode('/n', $lines);
答案 0 :(得分:0)
如果您尝试按行分割,则应使用:
$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,依此类推......
答案 1 :(得分:0)
我不确定为什么爆炸对你不起作用(它应该)。我建议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
。您必须使用双引号将其视为换行符。
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