Search code examples
phpregexpreg-matchsubstr

How to split data from a single word string in PHP?


I need to split data from a single word string like below,

$string = "RC9999999999A202";

//Need to split as follows:  

$code = "RC"; //This value must be of 2 alphabetic characters
$phone = "9999999999"; //This value must be of 10 digits
$amount = "202"; //This value can be of any length (numeric only)  

I tried nothing because I don't have any idea regarding this since I'm a newbie.

Please help!

Please do not leave negative rating, instead try to help me.


Solution

  • This will match according to your specifications and populate the variables code, phone and amount.

    $string = "RC9999999999A202";
    
    Preg_match("/([A-Z]{2})(\d{10})A(\d+)/", $string, $match);
    
    List($string, $code, $phone, $amount) = $match;
    

    https://3v4l.org/QXVRA

    This pattern assumes the "A" is always an "A".
    You didn't mention it at all in the question so I assume it's always an "A".