52

In PHP 5.3 there is a nice function that seems to do what I want:

strstr(input,"\n",true)

Unfortunately, the server runs PHP 5.2.17 and the optional third parameter of strstr is not available. Is there a way to achieve this in previous versions in one line?

2
  • You might want to use double quotes around that \n. When I had it in single quotes when creating email content, the \n just came out as regular characters instead of the newline character.
    – Svish
    Feb 1, 2012 at 14:50
  • 1
    why the one line restriction ?
    – misterjinx
    Feb 1, 2012 at 14:51

11 Answers 11

127

For the relatively short texts, where lines could be delimited by either one ("\n") or two ("\r\n") characters, the one-liner could be like

$line = preg_split('#\r?\n#', $input, 2)[0];

for any sequence before the first line feed, even if it an empty string,

or

$line = preg_split('#\r?\n#', ltrim($input), 2)[0];

for the first non-empty string.

However, for the large texts it could cause memory issues, so in this case strtok mentioned below or a substr-based solution featured in the other answers should be preferred.

When this answer was first written, almost a decade ago, it featured a few subtle nuances

  • it was too localized, following the Opening Post with the assumption that the line delimiter is always a single "\n" character, which is not always the case. Using PHP_EOL is not the solution as we can be dealing with outside data, not affected by the local system settings
  • it was assumed that we need the first non-empty string
  • there was no way to use either explode() or preg_split() in one line, hence a trick with strtok() was proposed. However, shortly after, thanks to the Uniform Variable Syntax, proposed by Nikita Popov, it become possible to use one of these functions in a neat one-liner

but as this question gained some popularity, it's better to cover all the possible edge cases in the answer. But for the historical reasons here is the original solution:

$str = strtok($input, "\n");

that will return the first non-empty line from the text in the unix format.

However, given that the line delimiters could be different and the behavior of strtok() is not that straight, as "Delimiter characters at the start or end of the string are ignored", as it says the man page for the original strtok() function in C, now I would advise to use this function with caution.

7
  • I wouldn't say it's fastest (And I wouldn't bother myself with speed comparison at all) but it's apparently shortest Feb 1, 2012 at 15:22
  • 23
    Coding PHP for over a decade now and never saw this function :D +1
    – schmunk
    Jan 26, 2015 at 18:25
  • 4
    This includes the new line char. So $str = rtrim(strtok($input, "\n")); would make it perfect.
    – Armin
    Mar 13, 2017 at 20:07
  • 4
    will return first non-empty line Jun 8, 2017 at 23:58
  • 1
    Using PHP_EOL will avoid any UNIX/ WIndows entanglememnts.
    – alimack
    Jun 26, 2020 at 12:41
16

It's late but you could use explode.

<?php
$lines=explode("\n", $string);
echo $lines['0'];
?>
3
  • 8
    Why do you use string keys in this example? Should it be $lines[0]?
    – trejder
    Apr 9, 2014 at 13:45
  • 2
    Note: If you only need the first line, this is inefficient. E.g. if $string is a hundred megabytes and the first line is only some bytes, this solution wastes a hundred megabyte of memory and your script might even be terminated as you hit the memory limit. Aug 2, 2017 at 15:56
  • current(explode("\n", $string)); shortens this and solves the issue of intermediate variable and memory waste. Feb 17, 2018 at 6:38
7
$first_line = substr($fulltext, 0, strpos($fulltext, "\n"));

or something thereabouts would do the trick. Ugly, but workable.

3

try

substr( input, 0, strpos( input, "\n" ) )
2

echo str_replace(strstr($input, '\n'),'',$input);

1
list($line_1, $remaining) = explode("\n", $input, 2);

Makes it easy to get the top line and the content left behind if you wanted to repeat the operation. Otherwise use substr as suggested.

3
  • You can omit remaining though Feb 1, 2012 at 15:05
  • You could, but as I stated if you wanted the top X lines then using my original "list($line_1, $remaining) = explode("\n", $input, 2);" would allow a repetitive action. With this edit my post is rather meaningless!? Just seems like a very odd edit to make... Feb 1, 2012 at 20:38
  • Well for the consequent calls strtok still would be better. Feb 2, 2012 at 8:02
1

not dependent from type of linebreak symbol.

(($pos=strpos($text,"\n"))!==false) || ($pos=strpos($text,"\r"));

$firstline = substr($text,0,(int)$pos);

$firstline now contain first line from text or empty string, if no break symbols found (or break symbol is a first symbol in text).

1

try this:

substr($text, 0, strpos($text, chr(10)))
0

You can use strpos combined with substr. First you find the position where the character is located and then you return that part of the string.

$pos = strpos(input, "\n");

if ($pos !== false) {
echo substr($input, 0, $pos);
} else {
echo 'String not found';
}

Is this what you want ?

l.e. Didn't notice the one line restriction, so this is not applicable the way it is. You can combine the two functions in just one line as others suggested or you can create a custom function that will be called in one line of code, as wanted. Your choice.

1
  • one line restriction ? is there a reason for that ? you know you can always create your own function that can be called later in just one line of code, right ?
    – misterjinx
    Feb 1, 2012 at 14:51
0

Many times string manipulation will face vars that start with a blank line, so don't forget to evaluate if you really want consider white lines at first and end of string, or trim it. Also, to avoid OS mistakes, use PHP_EOL used to find the newline character in a cross-platform-compatible way (When do I use the PHP constant "PHP_EOL"?).

$lines = explode(PHP_EOL, trim($string));
echo $lines[0];
0

A quick way to get first n lines of a string, as a string, while keeping the line breaks.

Example 6 first lines of $multilinetxt

echo join("\n",array_splice(explode("\n", $multilinetxt),0,6));

Can be quickly adapted to catch a particular block of text, example from line 10 to 13:

echo join("\n",array_splice(explode("\n", $multilinetxt),9,12)); 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.