Obtain first line of a string in PHP

南楼画角 提交于 2019-12-02 20:06:14
Your Common Sense

here you go

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

strtok() Documentation

It's late but you could use explode.

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

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

try

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

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

try this:

substr($text, 0, strpos($text, chr(10))
Paul Norman
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.

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

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.

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];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!