Bijan
Bijan

Reputation: 8670

Return nth line

How do I return the nth line of a string in RegEx?

For example, if the string is:

This is line 1
Some other stuff
Return me!

How would I have it return the third line without matching text that is in the third line?

I found this to return the first line but I am not sure how to modify it to return any other line #

Upvotes: 0

Views: 1631

Answers (3)

user557597
user557597

Reputation:

You can use the \K construct.

 #  '/(?:.*\r?\n){2}\K.*/'

 (?: .* \r? \n ){2}         # Nth - 1 lines
 \K                         # Do not include previous in match
 .*                         # Nth line

Output:

 **  Grp 0 -  ( pos 34 , len 10 ) 
Return me!  

Upvotes: 1

Nathan
Nathan

Reputation: 1482

Here's another way to do it. This will only capture the line you want to return. However, dynamic's solution of using explode is more readable/maintainable.

The $lineNumber is using an offset of 0 for the line numbers.

$subject = "This is line 1\r\nSome other stuff\r\nReturn me!";

$lineNumber = 2;
preg_match("/(?:.*(?:(?:\r?\n)|(?:\r\n?))?){" . (($lineNumber < 1) ? 0 : 1) . ",". $lineNumber ."}(.*(?:(?:\r?\n)|(?:\r\n?))?)/", $subject, $results);

echo $results[1];

Upvotes: 1

dynamic
dynamic

Reputation: 48141

This is not a good case for using regex. You can simply try this as @anubhava suggested:

$lines = explode("\n", $text);
echo $lines[2];

If you really want to use regex

$text="asdsa
asdas
sadas";

preg_match_all("|.+|",$text,$matches);
print_r($matches);
echo $matches[0][2];

http://ideone.com/mGRsdA

Upvotes: 2

Related Questions