0

We have a PHP regex check as follows to check if the string contains any number having length greater than 6 to validate pincode entered within the address string.

$str = "1234567test";
$pattern = "~\d[- /\d]*\d{6}\b~";

  if (preg_match_all($pattern, $str, $matches)) {
       echo "Yes";
    } else {
    echo "no";
    }

For the string 1234567 test it is matching as expected but why it is failing for the string such as 1234567test?

mpsbhat
  • 2,733
  • 12
  • 49
  • 105
  • You are matching a word-boundary which there is none after the digits in the 2nd string you have tested. – JvdV Aug 23 '21 at 10:31
  • You need digit boundaries, not word boundaries, `"~(?<!\d)\d[- /\d]*\d{6}(?!\d)~"` – Wiktor Stribiżew Aug 23 '21 at 10:35
  • @JvdV So this `~\d[- /\d]*\d{6}~` will do the job? – mpsbhat Aug 23 '21 at 10:38
  • 1
    This is actually more a question to you. – Wiktor Stribiżew Aug 23 '21 at 10:41
  • @mpsbhat, It may do the job yes, however we don't know what it is you are trying to validate/match exactly. If `"1//////// ------123456789etcetcetc"` is valid input then yes. – JvdV Aug 23 '21 at 10:41
  • Thanks @JvdV, We are trying to check if the string contains any number having length greater than 6 to validate pincode entered within the address string. – mpsbhat Aug 23 '21 at 10:44
  • Then you just need to remove word boundary. – Wiktor Stribiżew Aug 23 '21 at 10:45
  • 1
    Oke, well please go ahead and update your question with all relevant information. What do you want to match (samples are welcome)? What do you not want to match (again, samples) etc. So others don't have to go through the comment section to find all relevant information in their attempt to answer you. – JvdV Aug 23 '21 at 10:45
  • The linked dupe won't really help you IMO, but for people to re-open your question to be able to answer it I do believe you may want to add clarity as mentioned in my comment above. – JvdV Aug 23 '21 at 10:50

0 Answers0