如果字符串以“xx”开头(PHP)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5834907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:37:49 来源:igfitidea点击:
if string begins with "xx" (PHP)
提问by Riki137
if ($_POST['id'] beginsWith "gm") {
$_SESSION['game']=="gmod"
}
if ($_POST['id'] beginsWith "tf2") {
$_SESSION['game']=="tf2"
}
How to do this so it will work?
如何做到这一点,所以它会起作用?
采纳答案by Rocket Hazmat
if (strpos($_POST['id'], "gm") === 0) {
$_SESSION['game'] ="gmod"
}
if (strpos($_POST['id'],"tf2") === 0) {
$_SESSION['game'] ="tf2"
}
回答by Matt
回答by Jon
回答by Toto
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"
}
回答by PeeHaa
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 =
请注意,在为变量赋值时使用单个 =