如果字符串以“xx”(PHP)开头


if string begins with "xx" (PHP)

if ($_POST['id'] beginsWith "gm") {
$_SESSION['game']=="gmod"
}
if ($_POST['id'] beginsWith "tf2") {
$_SESSION['game']=="tf2"
}

如何做到这一点才能工作?

你可以使用子字符串

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
if (strpos($_POST['id'], "gm") === 0) {
  $_SESSION['game'] ="gmod"
}
if (strpos($_POST['id'],"tf2") === 0) {
  $_SESSION['game'] ="tf2"
}
不是

最快的方法,但您可以使用正则表达式

if (preg_match("/^gm/", $_POST['id'])) {
    $_SESSION['game']=="gmod"
}
if (preg_match("/^tf2/, $_POST['id'])) {
    $_SESSION['game']=="tf2"
}
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';
}

请注意,将值分配给变量时,请使用单个 =