views:

127

answers:

4

Hy i have to test if a string begins with 00 or with + 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? I hope i could explain my question clear?

+1  A: 
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.

Coronatus
can i alos do it with a regex i did iwth this cond. if(!preg_match("#^(\+|00){\d,2}#",$str)
streetparade
Why are you asking me if you can do it, when the next sentence says you have done it?
Coronatus
A: 
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;
KennyTM
+1  A: 
Matt Blaine
Does not meet the requirement of atleast 2 digits after 00 or +.
codaddict
@codaddict You are absolutely correct. That should be better.
Matt Blaine
@codaddict Ya know what? Your answer's better. I didn't read the question close enough.
Matt Blaine
+3  A: 

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;
    }
}
codaddict