StevenPHP
StevenPHP

Reputation: 3597

php split string on first occurrence of a letter

I have the following string

$string = "18/05-01/06 01/06-06/07 06/07-22/08 22/08-14/09 DR Record + 2 21.47 20.24 27.15 20.24 BE Record + 2 24.05 22.68"

I would like to split it at the first letter found (the letter varies each time). I found a similar question that had the following example

$split = explode('-', 'orange-yellow-red',2);
echo $split[1]; //output yellow-red

But this is assuming you know what the letter is. Is there a way to specify any letter? I've used preg split before but that can't limit and also i'm not that good with regex.

If explode would work with regex then something like this may work, but this is just an example as this would not work.

$string = "18/05-01/06 01/06-06/07 06/07-22/08 22/08-14/09 DR Record + 2 21.47 20.24 27.15 20.24";
$split = explode([A-Za-z], $string,2);

Upvotes: 1

Views: 3936

Answers (2)

FrankieTheKneeMan
FrankieTheKneeMan

Reputation: 6800

Try preg_split.

preg_split('/[a-z]/i', $string, 2);

I see you want to keep the letter - if you want it to go with the string before, use a lookbehind:

preg_split('/(?<=[a-z])/i', $string, 2);

if you want it to go with the string after, use a lookahead:

preg_split('/(?=[a-z])/i', $string, 2);

If you want it separated, up the number of splits and use both.

preg_split('/(?<=[a-z])|(?=[a-z])/i', $string, 3);

Here you go: see it in action

Upvotes: 3

Patrick Evans
Patrick Evans

Reputation: 42736

Use preg_split

$string = "18/05-01/06 01/06-06/07 06/07-22/08 22/08-14/09 DR Record + 2 21.47 20.24 27.15 20.24 BE Record + 2 24.05 22.68"

$stringArray = preg_split("/[a-zA-Z]/",$string,2);

the [a-zA-Z] tells it to find the first letter, and then it will split from there

$stringArray will hold the two resulting strings, note that it takes out the letter that it split on

You could though use preg_match to get the two strings so that it will not strip out the first letter

preg_match("/([^a-zA-Z]+)(.*)/",$string,$Matches);

here the regular expression tells it to capture everything up to the first letter, and then capture everything after that

$Matches[1] would contain

18/05-01/06 01/06-06/07 06/07-22/08 22/08-14/09 

and $Matches[2] would contain

DR Record + 2 21.47 20.24 27.15 20.24 BE Record + 2 24.05 22.68

$Match[0] holds the whole string that was matched.

Upvotes: 1

Related Questions