2010-03-29 44 views
0

我必须测试字符串是以还是以+开头。Preg_match如果字符串以“00”{数字}或“+”{number}开头

伪代码:

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?

+0

选择我的答案@streetparade谢谢,但看看由codaddict答案。 – 2010-03-29 09:17:23

+0

if(preg_match(“!^(?: 00 | \ +)(?:\ d \ d)!”,$ input)> 0){}请参阅codaddict的[answer](#2536697)。 – 2010-03-29 08:43:30

回答

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
if (substr($str, 0, 2) === '00') 
{ 
    return true; 
} 
elseif ($str[0] === '+') 
{ 
    $str = '00'.substr($str, 1); 
    return true; 
} 
else 
{ 
    return false; 
} 

虽然中间条件不会做任何事情,除非$ str是一个引用。

+0

我可以做一个正则表达式我做了这个cond。 if(!preg_match(“#^(\ + | 00){\ d,2}#”,$ str) – streetparade 2010-03-29 08:44:40

+0

为什么你问我是否可以做到这一点,当下一句说明你做到了? – 2010-03-29 08:49:30

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;