views:

39

answers:

3

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')

A: 

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

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

I tested and it works fine.

The limit argument:

If specified, then only substrings up to limit are returned with the rest of the string being placed in the last substring. A limit of -1, 0 or null means "no limit" and, as is standard across PHP, you can use null to skip to the flags parameter.

Update:

If it is only new line you want to split:

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

Or you can if you insist on preg_split();:

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

There's no preg_split_once() or any equivalent.

thephpdeveloper
+2  A: 

Just add the limit flag

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

From the manual

If specified, then only substrings up to limit are returned with the rest of the string being placed in the last substring.

RMcLeod
You can't, because it substrings.
thephpdeveloper
Mauris: the meaning of your comment is not clear, please explain
Ben James
I tested this out, and it works great! Thanks
albus
A: 

I don't have a server to test this on. Try:

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

The 1 represents the limit:

Limit: If specified, then only substrings up to limit are returned with the rest of the string being placed in the last substring. A limit of -1, 0 or null means "no limit" and, as is standard across PHP, you can use null to skip to the flags parameter.

greggannicott
RMcleod beat me to it. :-)
greggannicott
it substrings, you can't use the $limit flag.
thephpdeveloper
A limit of 1 will not split the string at all.
Ben James
@Ben: I could obviously be wrong, but when applying the manual to Albus' requested, and assuming a limit of one, it would read as:"If specified, then only substrings up to 1 are returned with the rest of the string being placed in the last substring."To me that implies that regardless of the limit you specify (eg. $limit), there will always be a resulting substring with a value of $limit+1 which contains the remainder of the content.
greggannicott
Based on RMcLeod's accepted response, I conceed defeat on this one. Even 'rtfm' doesn't work with me, as I misunderstand it :-)
greggannicott