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?

kinokijuf
  • 968
  • 1
  • 11
  • 33
  • 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 01 '12 at 14:50
  • 1
    why the `one line` restriction ? – misterjinx Feb 01 '12 at 14:51

11 Answers11

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.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
16

It's late but you could use explode.

<?php
$lines=explode("\n", $string);
echo $lines['0'];
?>
Connor Gurney
  • 699
  • 6
  • 15
  • 8
    Why do you use string keys in this example? Should it be `$lines[0]`? – trejder Apr 09 '14 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. – Christopher K. Aug 02 '17 at 15:56
  • `current(explode("\n", $string));` shortens this and solves the issue of intermediate variable and memory waste. – But those new buttons though.. Feb 17 '18 at 06:38
7
$first_line = substr($fulltext, 0, strpos($fulltext, "\n"));

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

Marc B
  • 356,200
  • 43
  • 426
  • 500
3

try

substr( input, 0, strpos( input, "\n" ) )
Sirko
  • 72,589
  • 19
  • 149
  • 183
2

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

Krimo
  • 954
  • 8
  • 20
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)))
mignz
  • 3,648
  • 2
  • 20
  • 21
Andrés Torres
  • 747
  • 5
  • 16
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.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Paul Norman
  • 1,621
  • 1
  • 9
  • 20
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];
Benjamin
  • 558
  • 7
  • 15
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)); 
NVRM
  • 11,480
  • 1
  • 88
  • 87
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.

misterjinx
  • 2,606
  • 3
  • 27
  • 29
  • 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 01 '12 at 14:51