I know "explode" splits the string and turns it into an array for every occurrence. But how do I split on the first occurrence and keep everything after the first occurrence?
Examples:
$split = explode('-', 'orange-yellow-red'); echo $split[1]; // output: "yellow"
^ I would like this to output: yellow-red
$split = explode('-', 'chocolate-vanilla-blueberry-red'); echo $split[1]; // output: "vanilla"
^ I would like this to output: vanilla-blueberry-red
To split a string and get the first element of the array, call the split() method on the string, passing it the separator as a parameter, and access the array element at index 0 . For example, str. split(',')[0] splits the string on each comma and returns the first array element. Copied!
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 .
You can pass the limit
as the third parameter of explode
that will do the job.
$split = explode('-', 'orange-yellow-red',2); echo $split[1]; //output yellow-red
Have a look at the third parameter of explode
:
$limit
If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.
If the limit parameter is negative, all components except the last -limit are returned.
If the limit parameter is zero, then this is treated as 1.
$a=explode('-','chocolate-vanilla-blueberry-red', 2); echo $a[1]; // outputs vanilla-blueberry-red
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