Reputation: 8670
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
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
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
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];
Upvotes: 2