正则表达式在第一个换行符时分割字符串

del*_*er2 5 php regex

我想在第一个换行符处拆分一个字符串,而不是第一个空白行

' /^(.*?)\r?\n\r?\n(.*)/s'(第一个空白行)

例如,如果我有:

$ str ='2099 test \n你确定要继续\n其他字符串在这里......';

match[1] = '2099 test'
match[2] = 'Are you sure you want to continue\n some other string here...'
Run Code Online (Sandbox Code Playgroud)

Rii*_*imu 12

preg_split()有一个限制参数,你可以利用它.你可以简单地做:

$lines = preg_split('/\r\n|\r|\n/', $str, 2);
Run Code Online (Sandbox Code Playgroud)


Mik*_*wis 6

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

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


?>
Run Code Online (Sandbox Code Playgroud)

回报

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

explode的最后一个参数是要将字符串拆分为的元素数.


Aka*_*run 1

通常只需删除\r?\n

'/^(.*?)\r?\n(.*)/s'
Run Code Online (Sandbox Code Playgroud)