如果字符串以“00”{number}或“+”{number}开头,则为Preg_match

时间:2010-03-29 08:33:08

标签: php regex preg-replace

我必须测试字符串是否以 00 + 开头。

伪代码:

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

最后两位数字可以是0-9 我怎么在PHP中这样做?

3 个答案:

答案 0 :(得分:5)

您可以尝试:

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

答案 1 :(得分:1)

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

中间条件不会做任何事情,除非$ str是参考。

答案 2 :(得分:0)

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;
相关问题