PHP Preg_split_once

Preg_match gives one match. Preg_match_all returns all matches. Preg_split returns all splits.

How can I split only the first match?

Example:

preg_split ("~ \ n ~", $ string);

This is what I want:

array (0 => 'first piece', 1 => 'the rest of the string without any further splits')

+5
source share
3 answers

Just set $ limit to 2for two parts of the array. Thanks to Ben James for mentioning:

preg_split("~\n~",$string, 2);

I tested and works great.

Marginal argument:

, , . -1, 0 null " " , PHP, null flags.

:

, :

$fp = strpos($string,"\n");
$arr = new array(substr($string,0,$fp), substr($string,$fp));

, preg_split();:

$fp = strpos($string,"\n");
$arr = preg_split("~\n~",$string,$fp);

preg_split_once() .

+10

preg_split("~\n~", $string, 2);

manual

, , .

+5

. :

preg_split("~\n~",$string,1);

1 :

: , , . -1, 0 null " " , PHP, null, flags.

0

All Articles