Home > Software engineering >  php preg_match() inside multiple separator
php preg_match() inside multiple separator

Time:12-28

I have string:

$data = "012.03.AB";

I want preg_match for:
012 = numeric & 3 digits
03 = numeric & 2 digits
AB = alphabet & 2 digits

This is my code:

$data = "012.03.AB";
preg_match("/[0-9]{3}\.[0-9]{2}|\.([A-Z]{2})/", $data);

but not working

CodePudding user response:

If i understand you correctly, your problems are:

  • You have a loose | in the middle of your pattern
  • Your second subpattern is set to be 3 digits, but you said it should be 2 digits
  • (may or may not be on purpose) your pattern isn't anchored

if (preg_match('#^([0-9]{3})\.([0-9]{2})\.([A-Z]{2})$#D', $data, $result) === 1) {
    // $data matched; you can use the segments as:
    $first  = (int) $result[1];
    $second = (int) $result[2];
    $third  =       $result[3];
} else {
    // $data did not match
}

You may want to add an i flag at the end if the 2 characters are allowed to be lowercase aswell.

  •  Tags:  
  • php
  • Related