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'
)
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('-'); .
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With