簡體   English   中英

如何使用PHP中的preg_match_all函數從peragraph獲取新行?

[英]How to get a new line from peragraph using preg_match_all function in php?

我有一個帶一些新行的peragraph:

 First line

Second line

Third line

 And this is the last line

我想從上面的peragraph中獲得第二行。

所以我想要的結果應該是:

 "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);

您是否知道如何從段落中獲得第二行?

任何幫助都非常有用。

謝謝!

嘗試這個:

$pera="First line

 Second line

 Third line

 And this is the last line";


$results = explode("\n", $pera);
print_r($results[2]);

僅出於演示目的, explode確實在性能上更好,但是如果您確實希望/必須使用正則表達式,則不要使用preg_match_all 這使它成為全局的,但是您不需要這樣做,因此請使用preg_match 然后,更改模式:

\n{2}.*

這將與第二行匹配,包括前導換行符。

https://regex101.com/r/jA3dL9/1

如果要不使用換行符,請使用捕獲組:

\n{2}(.*)

嘗試:

$data = array_values(
    array_filter(
        explode("\r\n", $pera) // or just \n
    )
);

echo $data[1]; // n°line - 1

演示:http: //3v4l.org/gpgOj

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM