Sateesh
Sateesh

Reputation: 11

Get a string between 2 strings in php

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

Answers (4)

KingCrunch
KingCrunch

Reputation: 131881

$lines = explode("\n", trim($string));
$lastLine = $lines[count($lines) - 1];

http://ideone.com/Qo8UY

or just (because when we trim the whitespaces away, we are looking for the last element)

$lastLine = end($lines);

http://ideone.com/DzvK6

Upvotes: 2

genesis
genesis

Reputation: 50976

$words = 'ABCDEF\nABCDEFGH\nABCDEFGHIJ\nABCDEFGHIJKLM\n';   
$words = explode('\n', $words);
$word = $words[count($words) - 2];

demo

Upvotes: 5

diagonalbatman
diagonalbatman

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

Yoshi
Yoshi

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

Related Questions