0

I've got string like this

$str = "cl2"

$str2 = "L1"

What i'm trying to get is the LAST NUMERIC NUMER and whatever is before the numeric number

Result I want is

$result[0] = "cl"
$result[1] = "2"

$result[0] = "L"
$result[1] = "1"

I've been looking at explode() and str_split() php functions to use but cant seem to find a way to only get the last digit, then everything else before it thanks

5

2 Answers 2

0

This is work for me.You can split whatever is before the numeric number

<?php
$str = "cl2";
$result = preg_split('/(?<=[a-z])(?=\d)/i', $str);
?>

Another way from @Marcus's answer

<?php
$str = "cl2";   
$result = preg_split("/(\d+)/", $str , -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);    
?>

Then result is :

$result[0] = "cl"
$result[1] = "2"
Sign up to request clarification or add additional context in comments.

Comments

0

Thanks guys, I ended up using substr to solve my problem

$str = "CL2"
$result[0] = substr($str, 0, -1); // returns "CL"
$result[1] = substr($str, -1); // returns "2"

1 Comment

A robust program would not only get the results you think you want, but verify that the right types of data have been acquired.

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.