-2

I would need to check in php if the number has 10 digit length and the first 2 digits need to be 09 and check for no space too please?

sample true number = 0912345678

Thanks Ramin

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Ramin Rabii
  • 359
  • 4
  • 14

1 Answers1

2

You can do that by using regular expressions, like this:

function checkNumber($number) {
    return !!preg_match('/^09\d{8}$/', "$number");
}

Or with simple string matching:

function checkNumber($number) {
    $number = trim("$number");
    if (strlen($number) != 10)
        return false;

    if (substr($number, 0, 2) != "09")
        return false;

    return trim($number, "0..9") == "";
}

Both methods gives same output:

var_dump([$number = '0912345678', checkNumber($number)]);
var_dump([$number = '9012345678', checkNumber($number)]);
var_dump([$number = '091234567', checkNumber($number)]);
var_dump([$number = '09123456788', checkNumber($number)]);

// array(2) {
//   [0]=>
//   string(10) "0912345678"
//   [1]=>
//   bool(true)
// }
// array(2) {
//   [0]=>
//   string(10) "9012345678"
//   [1]=>
//   bool(false)
// }
// array(2) {
//   [0]=>
//   string(9) "091234567"
//   [1]=>
//   bool(false)
// }
// array(2) {
//   [0]=>
//   string(11) "09123456788"
//   [1]=>
//   bool(false)
// }

Also, regexp approach is more simpler and flexible, imho.

ankhzet
  • 2,517
  • 1
  • 24
  • 31
  • 1
    Please add some information about how your code solves the Problem. – Koopakiller Aug 16 '15 at 12:07
  • thanks so much. very helpful. I also tried below code and it worked too. preg_match("/^([09]{2})([0-9]{9})$/", $cellNum) – Ramin Rabii Aug 16 '15 at 13:22
  • @RaminRabii, but yours code gives `true` for numbers of 11 digits, also they can start with `09` **and** `90`, as `[09]{2}` means "two digits of `0` and `9`, in any order" – ankhzet Aug 16 '15 at 13:28
  • thanks so much for your advise. should change it to preg_match("/^([0]{1})([9]{1})([0-9]{8})$/", $cellNum); – Ramin Rabii Aug 17 '15 at 07:17
  • =) there are no meaning in `[0]{1}` or `[9]{1}` constructions, as they can be replaced with simple `0` and `9`. so, you can use one of this patterns: `/^(09)(\d{8})$/`, `/^(09)([0-9]{8})$/` – ankhzet Aug 17 '15 at 07:29