streetparade
streetparade

Reputation: 32878

Preg_match if a string beginns with "00"{number} or "+"{number}

I have to test if a string begins with 00 or with +.

pseudocode:

Say I have the string **0090** or **+41** 
if the string begins with **0090** return true,  
elseif string begins  with **+90** replace the **+** with **00**  
else return false

The last two digits can be from 0-9.
How do I do that in php?

Upvotes: 0

Views: 819

Answers (3)

codaddict
codaddict

Reputation: 454960

You can try:

function check(&$input) { // takes the input by reference.
    if(preg_match('#^00\d{2}#',$input)) { // input begins with "00"
        return true;
    } elseif(preg_match('#^\+\d{2}#',$input)) { // input begins with "+"
        $input = preg_replace('#^\+#','00',$input); // replace + with 00.
        return true;
    }else {
        return false;
    }
}

Upvotes: 5

kennytm
kennytm

Reputation: 523214

if (substr($theString, 0, 4) === '0090') {
  return true;
} else if (substr($theString, 0, 3) === '+90') {
  $theString = '00' . substr($theString, 1);
  return true;
} else
  return false;

Upvotes: 0

Amy B
Amy B

Reputation: 17977

if (substr($str, 0, 2) === '00')
{
    return true;
}
elseif ($str[0] === '+')
{
    $str = '00'.substr($str, 1);
    return true;
}
else
{
    return false;
}

The middle condition won't do anything though, unless $str is a reference.

Upvotes: 1

Related Questions