开发者

regex split string at first line break

I would like to split a string at the first line break, instead of the first blank line

'/^(.*?)\r?\n\r?\n(.*)/s' (first blank line)

So for instance, if I have:

$str = '2099 test\nAre you sure you want to continue\n some other string开发者_运维问答 here...';

match[1] = '2099 test'
match[2] = 'Are you sure you want to continue\n some other string here...'


preg_split() has a limit parameter you can take to your advantage. You could just simply do:

$lines = preg_split('/\r\n|\r|\n/', $str, 2);


<?php
$str = "2099 test\nAre you sure you want to continue\n some other string here...";

$match = explode("\n",$str, 2);
print_r($match);


?>

returns

Array
(
    [0] => 2099 test
    [1] => Are you sure you want to continue
 some other string here...
)

explode's last parameter is the number of elements you want to split the string into.


Normally just remove on \r?\n:

'/^(.*?)\r?\n(.*)/s'


You can use preg_split as:

$arr = preg_split("/\r?\n/",$str,2);

See it on Ideone


First line break:

$match = preg_split('/\R/', $str, 2);

First blank line:

$match = preg_split('/\R\R/', $str, 2);

Handles all the various ways of doing line breaks.

Also there was a question about splitting on the 2nd line break. Here is my implementation (maybe not most efficient... also note it replaces some line breaks with PHP_EOL)

function split_at_nth_line_break($str, $n = 1) {
    $match = preg_split('/\R/', $str, $n+1);
    if (count($match) === $n+1) {
        $rest = array_pop($match);
    }
    $match = array(implode(PHP_EOL, $match));
    if (isset($rest)) {
        $match[] = $rest;
    }
    return $match;
}

$match = split_at_nth_line_break($str, 2);


Maybe you don't even need to use regex's. To get just split lines, see:

What's the simplest way to return the first line of a multi-line string in Perl?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜