Obtain first line of a string in PHP

后端 未结 11 1117
醉话见心
醉话见心 2021-02-01 13:14

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

相关标签:
11条回答
  • 2021-02-01 13:58

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

    0 讨论(0)
  • 2021-02-01 13:59
    $first_line = substr($fulltext, 0, strpos($fulltext, "\n"));
    

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

    0 讨论(0)
  • 2021-02-01 14:02

    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];
    
    0 讨论(0)
  • 2021-02-01 14:04

    try this:

    substr($text, 0, strpos($text, chr(10))
    
    0 讨论(0)
  • 2021-02-01 14:11
    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.

    0 讨论(0)
提交回复
热议问题