Amit Verma
Amit Verma

Reputation: 41249

Match a specific line in string using regex

I have a string that contains some substrings seperated by a new line.

Forexample :

$x="This is the first line.
      This is the second line.
      This is the third line.";

I want to get the third line from this string,

My regex so far :

/\s*([^\n]+)/i

But this returns the whole string,

I have also tried

/\n{3}\s*([^\n]+)/i

It matched nothing.

Is there any way in regex to solve my problem? I have been trying to solve it myself for the last 30mnts, but all of my attempts failed.

 preg_match_all("/\s*([^\n]+)/i",$x,$m);
print_r($m);

Thank you!

Upvotes: 1

Views: 666

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174826

Just use s modifier along with $ . In dotall mode $ matches the end of very last line.

preg_match('~\s*([^\n]+)$~s',$x,$m);

DEMO

Upvotes: 1

TwoStraws
TwoStraws

Reputation: 13127

Unless I'm misunderstanding the complexity of your situation, you should be able to just use explode() like this:

$split = explode("\n", $x);
print_r($split[2]);

Upvotes: 5

Related Questions