Obtain first line of a string in PHP

2019-03-10 16:01发布

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?

10条回答
走好不送
2楼-- · 2019-03-10 16:41

It's late but you could use explode.

<?php
$lines=explode("\n", $string);
echo $lines['0'];
?>
查看更多
唯我独甜
3楼-- · 2019-03-10 16:41

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];
查看更多
一夜七次
4楼-- · 2019-03-10 16:46

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

查看更多
Anthone
5楼-- · 2019-03-10 16:46

try this:

substr($text, 0, strpos($text, chr(10))
查看更多
啃猪蹄的小仙女
6楼-- · 2019-03-10 16:51
$first_line = substr($fulltext, 0, strpos($fulltext, "\n"));

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

查看更多
干净又极端
7楼-- · 2019-03-10 16:56

try

substr( input, 0, strpos( input, "\n" ) )
查看更多
登录 后发表回答