Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a string on the first occurrence of something?

Tags:

php

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

like image 493
supercoolville Avatar asked Dec 28 '11 09:12

supercoolville


People also ask

How do you get the first element to split?

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!

How do you split a string at first instance 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 .


2 Answers

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 
like image 69
Shakti Singh Avatar answered Sep 18 '22 22:09

Shakti Singh


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 
like image 27
Maerlyn Avatar answered Sep 21 '22 22:09

Maerlyn