53

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. Commented Feb 1, 2012 at 14:50
  • 1
    why the one line restriction ? Commented Feb 1, 2012 at 14:51

11 Answers 11

129

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.

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

7 Comments

I wouldn't say it's fastest (And I wouldn't bother myself with speed comparison at all) but it's apparently shortest
Coding PHP for over a decade now and never saw this function :D +1
This includes the new line char. So $str = rtrim(strtok($input, "\n")); would make it perfect.
will return first non-empty line
Using PHP_EOL will avoid any UNIX/ WIndows entanglememnts.
|
16

It's late but you could use explode.

<?php
$lines=explode("\n", $string);
echo $lines['0'];
?>

3 Comments

Why do you use string keys in this example? Should it be $lines[0]?
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.
current(explode("\n", $string)); shortens this and solves the issue of intermediate variable and memory waste.
7
$first_line = substr($fulltext, 0, strpos($fulltext, "\n"));

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

Comments

3

try

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

Comments

2

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

Comments

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

You can omit remaining though
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...
Well for the consequent calls strtok still would be better.
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).

Comments

1

try this:

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

Comments

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 Comment

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 ?
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];

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.