开发者

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\nABCDEFG开发者_开发百科HIJKLM\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


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

demo


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


$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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜