简体   繁体   中英

PHP preg_plit() with line breaks but prevent multi line jumps

I would like to preg_split() a string every new line, only line with content (no multi line jumps)

I tried this (\\S*)\\n|$

For example:

last_name, first_name

bjorge, philip
kardashian, kim
mercury, freddie

my preg_split

(\S*)\n|$
array(2
0   =>  last_name, first_name
1   =>  
)
array(2
0   =>  
1   =>  
)
array(2
0   =>  bjorge, philip
1   =>  
)
array(2
0   =>  kardashian, kim
1   =>  
)
array(2
0   =>  mercury, freddie
1   =>  
)

What I would like as an array:

array(2
0   =>  last_name, first_name
)
array(2
0   =>  bjorge, philip
)
array(2
0   =>  kardashian, kim 
)
array(2
0   =>  mercury, freddie    
)

Split on \\R+ that means 1 or more any kind of linebreak.

Edit according to comment:

In order to not capture lines that contain only spaces, add \\h+ (ie 1 or more horizontal spaces):

$string = "last_name, first_name

bjorge, philip
kardashian, kim
mercury, freddie
";
$res = preg_split('/\h*\R+/', $string, -1, PREG_SPLIT_NO_EMPTY);
print_r($res);

Output:

Array
(
    [0] => last_name, first_name
    [1] => bjorge, philip
    [2] => kardashian, kim
    [3] => mercury, freddie
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM