Obtain first line of a string in PHP

后端 未结 11 1116
醉话见心
醉话见心 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:48

    here you go

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

    strtok() Documentation

    0 讨论(0)
  • 2021-02-01 13:49

    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)); 
    
    0 讨论(0)
  • 2021-02-01 13:52

    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.

    0 讨论(0)
  • 2021-02-01 13:55

    It's late but you could use explode.

    <?php
    $lines=explode("\n", $string);
    echo $lines['0'];
    ?>
    
    0 讨论(0)
  • 2021-02-01 13:55

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

    0 讨论(0)
  • 2021-02-01 13:56

    try

    substr( input, 0, strpos( input, "\n" ) )
    
    0 讨论(0)
提交回复
热议问题