0

I need to split this format of strings CF12:10 into array like below,

[0] => CF, [1] => 12, [2] => 10

Numbers and String of the provided string can be any length. I have found the php preg_match function but don't know how to make regular expression for my case. Any solution would be highly appreciated.

2 Answers 2

1

You could use this regex to match the individual parts:

^(\D+)(\d+):(.*)$

It matches start of string, some number of non-digit characters (\D+), followed by some number of digits (\d+), a colon and some number of characters after the : and before end-of-line. In PHP you can use preg_match to then find all the matching groups:

$input = 'CF12:10';
preg_match('/^(\D+)(\d+):(.*)$/', $input, $matches);
array_shift($matches);
print_r($matches);

Output:

Array
(
    [0] => CF
    [1] => 12
    [2] => 10
)

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

1 Comment

This is what i expected, Thanks lot :)
0

Try the following code if it helps you

 $str = 'C12:10';
 $arr = preg_match('~^(.*?)(\d+):(.*)~m', $str, $matches);
 array_shift($matches);                                                   
 echo '<pre>';print_r($matches);

1 Comment

You can explode with : first like this. $arr = explode(‘:’,$string) and then run the above code on $arr[0] and $arr[1] will already be equal to 10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.