开发者

if string begins with "xx" (PHP) [duplicate]

This question already has answers here: How to check if a string starts with a specified string? [duplicate] (5 answers) Closed 8 years ago.
if ($_POST['id'] beginsWith "gm") {
$_SESSION['game']=="gmod"
}
if ($_POST['id'开发者_JS百科] beginsWith "tf2") {
$_SESSION['game']=="tf2"
}

How to do this so it will work?


You could use substring

if(substr($POST['id'],0,3) == 'tf2')
 {
  //Do something
 }

Edit: fixed incorrect function name (substring() used, should be substr())


You can write a begins_with using strpos:

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


NOT the fastest way to do it but you can use regex

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

Note that when assigning values to variable use a single =

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜