Obtener la primera línea de una cadena en PHP

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?

preguntado el 01 de febrero de 12 a las 14:02

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. -

por qué el one line restriction ? -

11 Respuestas

Given that a line could be delimited by either one ("\n") or two ("\r\n") characters, the most bullet-proof method would be

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

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

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

for the first non-empty string.

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 Sintaxis de variable uniforme, propuesto por Nikita Popov, it become possible to use one of these functions in a neat one-liner

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

$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.

contestado el 31 de mayo de 21 a las 07:05

I wouldn't say it's fastest (And I wouldn't bother myself with speed comparison at all) but it's apparently más corto - Tu sentido común

Coding PHP for over a decade now and never saw this function :D +1 - schmunk

I've used this snippet to obtain the first line of a soap response header: echo strtok($client->__getLastResponseHeaders(), "\n"); => ".1 200 OK" - Victor Marconi

This includes the new line char. So $str = rtrim(strtok($input, "\n")); would make it perfect. - Armin

will return first no vacio línea - ambientalhack

It's late but you could use explode.

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

respondido 07 nov., 12:00

Why do you use string keys in this example? Should it be $lines[0]? - trejder

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.

current(explode("\n", $string)); shortens this and solves the issue of intermediate variable and memory waste. - Billynoah

$first_line = substr($fulltext, 0, strpos($fulltext, "\n"));

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

Respondido 01 Feb 12, 18:02

tratan

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

Respondido 01 Feb 12, 18:02

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

Respondido 01 Feb 12, 18:02

prueba esto:

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

Respondido 01 Feb 12, 18:02

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.

Respondido 02 Feb 12, 07:02

You can omit remaining though - Tu sentido común

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... - Paul Norman

Well for the consequent calls strtok still would be better. - Tu sentido común

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

Respondido el 05 de Septiembre de 15 a las 19:09

Puede usar el strpos combinado con 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';
}

Es esto lo que quieres ?

le 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.

Respondido 01 Feb 12, 19:02

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

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 (¿Cuándo utilizo la constante de PHP "PHP_EOL"?).

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

Respondido 07 Feb 18, 05:02

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

Respondido el 01 de diciembre de 19 a las 09:12

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.