PHP regular expression string starting with specific characters and followed by numbers

I am trying to create a regex to test my code. The rules are as follows:

  • It starts with B or J or 28
  • The total line length must be 7 or 13 characters (including start characters)
  • The characters following the start characters must be all digits

Can anyone help me with this? Thanks to

I have tried something like

$pattern = "/^((J|B|28)([0-9])({7}|{13})?/i";

      

But this doesn't work: \

+3


source to share


2 answers


$pattern = "/^(?=(.{7}|.{13})$)(B|J|28)\d+$/";

      



+6


source


First use the following regex to match the pattern. It will capture the first ID in the first group and the next digits in the second group.

<?php 
$pattern = "/^(B|J|28)([0-9]+)$/i"; 
?>

      



Then run strlen()

to check the length. Regular expressions are not a good tool for checking variable lengths across groups.

<?php 
$hasValidLength = strlen( $str ) === 7 || strlen( $str ) === 13; 
?>

      

+1


source







All Articles