2010-03-29 128 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; 
相關問題