2

I have a peragraph with some new lines :

 First line

Second line

Third line

 And this is the last line

I want to get the second line from the above peragraph.

So the result I want should be :

 "Second line"

I have tried the following script with preg_match_all() function but I don't know why it's not working.

 <?php
 $pera="First line

 Second line

 Third line

  And this is the last line";


 preg_match_all("#\n+{2}.*+#",$pera,$results);
print_r($results);

Do you have any idea how to get the second line from the paragraph?

Any help is much appriciated.

Thanks!

Amit Verma
  • 40,709
  • 21
  • 93
  • 115

3 Answers3

2

Try this:

$pera="First line

 Second line

 Third line

 And this is the last line";


$results = explode("\n", $pera);
print_r($results[2]);
Tomasz Racia
  • 1,786
  • 2
  • 15
  • 23
2

Only for the purpose demonstrated, explode is really better for performance, but if you do want/have to use regex, don't use preg_match_all. That makes it global but you don't need that so go with preg_match. Then, change the pattern:

\n{2}.*

This will match the second line including leading newline character.

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

If you want to match w/o the newline, use a capturing group:

\n{2}(.*)
marekful
  • 14,986
  • 6
  • 37
  • 59
  • 3
    You should change `.*` to `.+` in case there are three consecutive newlines and `\n` to `\R` to handle any kind of newline sequence whatever the OS. – Casimir et Hippolyte May 25 '15 at 13:07
1

Try with:

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

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

Demo: http://3v4l.org/gpgOj

Federkun
  • 36,084
  • 8
  • 78
  • 90