我试图将用户输入的单词与$patterns数组中存储的模式相匹配,但preg_match函数仅返回false值。
<?php
$patterns = array(
"p1"=>array("/^t[a-z]*s$/i","start with 't' and end with 's'"),
"p2"=>array("/^c[a-z]*e$/i","start with 'c' and end with 'e'"),
"p3"=>array("/^p[a-z]*t$/i"," start with 'p' and end with 't'"),
"p4"=>array("/^b[a-z]*y$/i"," start with 'b' and end with 'y'"),
"p5"=>array("/^w[a-z]*r$/i","start with 'w' and end with 'r'"),
"p6"=>array("/^d[a-z]*n$/i","start with 'd' and end with 'n'"));
$randomKey = array_rand($patterns);
// print_r($patterns[$random]);
// print_r($patterns);
// print_r($patterns[$randomKey][0]);
// print_r($patterns[$randomKey][1]);
$randomValue1 = $patterns[$randomKey][0];
$randomValue2 = $patterns[$randomKey][1];
?>
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title>Word Challange</title>
</head>
<body>
<div class="container">
<h1 class="display-4">Word Challange Game</h1>
<h3>Enter a Word that <?php echo $randomValue2?> </h3>
<form method="POST">
<div class="form-group">
<input type="text" name="word" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter a word">
</div>
<input type="submit" class="btn btn-primary"></input>
<!-- <input type="reset" class="btn btn-primary"></input> -->
</form>
<?php
session_start();
if (!isset($_SESSION['counter'])) {
$_SESSION['score'] = 0;
}
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['word'])){
$word=$_POST['word'];
if(preg_match($randomValue1,$word)){
$_SESSION['score']++;
echo "Correct :) </br>";
echo "Score: ".$_SESSION['score'];
}
else{
echo "!!Incorrect Input!! Game Over :(</br>";
echo "Your Score: ".$_SESSION['score'];
$_SESSION['score'] = 0;
}
// echo "</br>".$patterns[$GLOBALS['random']][0];
}
}
?>
</div>
</body>
</html>
我正在尝试随机选择模式和模式消息。
1条答案
按热度按时间vaj7vani1#
实际上,并不总是这样。如果你输入了一个正确的答案,并且在POST之后,与前一个相同的模式被随机化,那么你将得到一个正确的答案:)
问题是,一旦你发布你的词,页面重新加载,并根据新的随机模式测试发布的词,而不是在发布之前询问的模式。为了确保它能正常工作,你需要知道POST之前的模式是什么,并根据它进行测试,而不是在POST之后随机化的模式。我使用一个名为
$_SESSION['pattern']
的会话变量来实现它:以上只是我需要应用更改的代码部分。