if ($_POST['id'] beginsWith "gm") {
$_SESSION['game']=="gmod"
}
if ($_POST['id'] beginsWith "tf2") {
$_SESSION['game']=="tf2"
}
怎麼做,所以它是否行得通呢?如果字符串以「XX」(PHP)開始
if ($_POST['id'] beginsWith "gm") {
$_SESSION['game']=="gmod"
}
if ($_POST['id'] beginsWith "tf2") {
$_SESSION['game']=="tf2"
}
怎麼做,所以它是否行得通呢?如果字符串以「XX」(PHP)開始
if (strpos($_POST['id'], "gm") === 0) {
$_SESSION['game'] ="gmod"
}
if (strpos($_POST['id'],"tf2") === 0) {
$_SESSION['game'] ="tf2"
}
這是錯誤的。如果strpos返回false,則這兩個if語句將評估爲true。 – andrewtweber 2011-04-29 17:01:47
@andrewtweber:有。用'==='替換'==':-P – 2011-04-29 17:13:14
你可以使用substring
if(substr($POST['id'],0,3) == 'tf2')
{
//Do something
}
編輯:固定不正確的函數名(用來substring()
,應該是substr()
)
可以使用strpos
寫begins_with
:
function begins_with($haystack, $needle) {
return strpos($haystack, $needle) === 0;
}
if (begins_with($_POST['id'], "gm")) {
$_SESSION['game']=="gmod"
}
// etc
function startswith($haystack, $needle){
return strpos($haystack, $needle) === 0;
}
if (startswith($_POST['id'], 'gm')) {
$_SESSION['game'] = 'gmod';
}
if (startswith($_POST['id'], 'tf2')) {
$_SESSION['game'] = 'tf2';
}
沒有TE是分配值的變量使用單一=
不這樣做的最快方法,但你可以使用正則表達式
if (preg_match("/^gm/", $_POST['id'])) {
$_SESSION['game']=="gmod"
}
if (preg_match("/^tf2/, $_POST['id'])) {
$_SESSION['game']=="tf2"
}
你必須寫在C代碼補丁,增加了這個關鍵字時/語法 – Gordon 2011-04-29 16:52:34