1

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

4 Answers 4

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

demo

Sign up to request clarification or add additional context in comments.

2 Comments

it doesn't matter, if you want fourth entry everytime
@gensis: But he doesn't want the fourth entry. "I need to get the sub string in between last 2 \ns."
2

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)?

Comments

2
$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

3 Comments

trim does not strip last \n ;)
@genesis: Thats wrong. var_dump(trim("abc\n")); string(3) "abc"
@genesis: explode() is executed after trim(), not before. This means, that only whitespaces (including newlines), that are not at the beginning, or the end of the string, remains before calling explode(). ideone.com/Qo8UY
0

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.

2 Comments

This function has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.
Ahh - apologies, i didn't realise. Noted. I will amend the answer to reflect.

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.