Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explode string only once on first occurring substring

preg_match() gives one match.
preg_match_all() returns all matches.
preg_split() returns all splits.

How can I split only on 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'
)
like image 683
albus Avatar asked Nov 03 '09 16:11

albus


People also ask

How do you split a string only on the first instance of specified character?

Use the String. split() method with array destructuring to split a string only on the first occurrence of a character, e.g. const [first, ... rest] = str. split('-'); .

How do you split a string with the first occurrence of a character in python?

Use the str. split() method with maxsplit set to 1 to split a string on the first occurrence, e.g. my_str. split('-', 1) . The split() method only performs a single split when the maxsplit argument is set to 1 .

How do you split the first string?

Using the split() Method For example, if we put the limit as n (n >0), it means that the pattern will be applied at most n-1 times. Here, we'll be using space (” “) as a regular expression to split the String on the first occurrence of space.

Which method allows you to break up a string into a list of substrings based on the separator you specify?

Split method. String. Split provides a handful of overloads to help you break up a string into a group of substrings based on one or more delimiting characters that you specify.


1 Answers

Simply set $limit to 2 for 2 parts of the array. Thanks to @BenJames 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.

like image 183
4 revs, 2 users 58% Avatar answered Oct 05 '22 04:10

4 revs, 2 users 58%