Obtain first line of a string in PHP
It's late but you could use explode.
<?php
$lines=explode("\n", $string);
echo $lines['0'];
?>
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()
orpreg_split()
in one line, hence a trick withstrtok()
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.