Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

php preg_match() inside multiple separator

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

but not working

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading