如何使用 php 中的 preg_match_all 函数从段落中获取新行?
How to get a new line from peragraph using preg_match_all function in php?
我有一个带有一些新行的段落:
First line
Second line
Third line
And this is the last line
我想从上面的段落中获取第二行。
所以我想要的结果应该是:
"Second line"
我已经用 preg_match_all() 函数尝试了以下脚本,但我不知道为什么它不起作用。
<?php
$pera="First line
Second line
Third line
And this is the last line";
preg_match_all("#\n+{2}.*+#",$pera,$results);
print_r($results);
你知道如何从段落中提取第二行吗?
非常感谢任何帮助。
谢谢!
试试:
$data = array_values(
array_filter(
explode("\r\n", $pera) // or just \n
)
);
echo $data[1]; // n°line - 1
试试这个:
$pera="First line
Second line
Third line
And this is the last line";
$results = explode("\n", $pera);
print_r($results[2]);
仅出于演示的目的,explode
的性能确实更好,但是如果您 want/have 使用正则表达式,请不要使用 preg_match_all
。这使它成为全球性的,但你不需要它,所以使用 preg_match
。然后,改变模式:
\n{2}.*
这将匹配第二行,包括前导换行符。
https://regex101.com/r/jA3dL9/1
如果要匹配 w/o 换行符,请使用捕获组:
\n{2}(.*)
我有一个带有一些新行的段落:
First line
Second line
Third line
And this is the last line
我想从上面的段落中获取第二行。
所以我想要的结果应该是:
"Second line"
我已经用 preg_match_all() 函数尝试了以下脚本,但我不知道为什么它不起作用。
<?php
$pera="First line
Second line
Third line
And this is the last line";
preg_match_all("#\n+{2}.*+#",$pera,$results);
print_r($results);
你知道如何从段落中提取第二行吗?
非常感谢任何帮助。
谢谢!
试试:
$data = array_values(
array_filter(
explode("\r\n", $pera) // or just \n
)
);
echo $data[1]; // n°line - 1
试试这个:
$pera="First line
Second line
Third line
And this is the last line";
$results = explode("\n", $pera);
print_r($results[2]);
仅出于演示的目的,explode
的性能确实更好,但是如果您 want/have 使用正则表达式,请不要使用 preg_match_all
。这使它成为全球性的,但你不需要它,所以使用 preg_match
。然后,改变模式:
\n{2}.*
这将匹配第二行,包括前导换行符。
https://regex101.com/r/jA3dL9/1
如果要匹配 w/o 换行符,请使用捕获组:
\n{2}(.*)