Reputation: 11
I am developing a website in php. I want to get a sub string in between two strings My main string is "ABCDEF\nABCDEFGH\nABCDEFGHIJ\nABCDEFGHIJKLM\n". I need to get the sub string in between last 2 \n s.(ABCDEFGHIJKLM)... Can you please help me for this issue.
Thanks Sateesh
Upvotes: 1
Views: 320
Reputation: 131881
$lines = explode("\n", trim($string));
$lastLine = $lines[count($lines) - 1];
or just (because when we trim the whitespaces away, we are looking for the last element)
$lastLine = end($lines);
Upvotes: 2
Reputation: 50976
$words = 'ABCDEF\nABCDEFGH\nABCDEFGHIJ\nABCDEFGHIJKLM\n';
$words = explode('\n', $words);
$word = $words[count($words) - 2];
Upvotes: 5
Reputation: 18002
You can use the Split()
function to tokenise the string. You can then locate the relevant part of the string....
http://php.net/manual/en/function.split.php
NOTE
As advised below the use of this function is no longer recomended as it has been Deprecated from the PHP spec from 5.3 onwards. The correct answer would be to use the Explode()
function - as shown in the other answers above.
Upvotes: 0
Reputation: 54649
If the number of \n
is unknown, you can use:
$string = "ABCDEF\nABCDEFGH\nABCDEFGHIJ\nABCDEFGHIJKLM\n";
$words = explode("\n", trim($string));
$last = array_pop($words);
echo $last;
Question: Do you want a newline ("\n") or literally '\n' (backslash n)?
Upvotes: 2