1

I want to validate using regex the user input to see if match the following rules.

Valid input:

2-000000000000
1-234342324342
...

Rules:

  1. It has to be 13 digit numbers, no string.
  2. Allow hyphen - come after the first character.
  3. Allow space before and after the hyphen - character.

Here's what I tried in PHP, but still not correct:

if(preg_match("/[0-9?\-[0-9]/i])) {

  echo "matched";

} 
5
  • 1
    Maybe preg_match("/^\d ?- ?\d{12}\z/", $string)? Note your string literal is malformed. Also, [0-9?\-[0-9] is a malformed regex that matches a digit, ?, - or [ chars. i is irrelevant here, there are no letters in the pattern. Commented Sep 2, 2022 at 6:49
  • 3
    You can use ^\d(?:\h*-\h*)?\d{12}$ Commented Sep 2, 2022 at 6:49
  • 1
    It has to be 13 digit numbers, no string. - regex works only on strings, also 2-000000000000 is not even a number in first place Commented Sep 2, 2022 at 6:56
  • @WiktorStribiżew - it works, thank for that. Regarding the space, how to allow one or more space? I test it and its only match one space, but I want to allow one or more spaces before and after the hyphen. Commented Sep 2, 2022 at 6:59
  • 1
    @mana: I have already provisioned for any no of spaces in my comment above Commented Sep 2, 2022 at 6:59

1 Answer 1

1

Note your double-quoted string literal is malformed, the closing " is missing.

Also, mind that [0-9?\-[0-9] is a malformed regex that matches a digit, ?, - or [ char. The i flag is irrelevant here, since there are no letters in the pattern.

I suggest using

preg_match("/^\d *- *\d{12}\z/", $string)

If the spaces can be any whitespace, replace the literal spaces with \s.

Note the use of \z anchor, I prefer it to $ in validation scenarios, since $ can match before the final line feed char in the string.

See the regex demo (\z replaced with $ since the input is a single multiline string there).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.