1

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!

2
  • 2
    Why not explode with \n and get the last item? A regex is necessary when you have complex patterns. Here, you need to get some specific line. Commented Dec 12, 2015 at 13:18
  • Could you provide a full example of the string you are trying to parse since you said this is only a small part of a bigger string you are trying to parse... Commented Dec 12, 2015 at 13:22

2 Answers 2

5

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]);
Sign up to request clarification or add additional context in comments.

1 Comment

Also trim the output, since it appears that $x contains leading spaces.
1

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

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

DEMO

1 Comment

You do not need /s. I doubt you need a regex at all here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.