1

所以我在这里有一些代码可以从标准的 Web 表单中获取用户输入:

if (get_magic_quotes_gpc()) {
    $searchsport = stripslashes($_POST['sport']);
    $sportarray = array(
        "Football" => "Fb01",
        "Cricket" => "ck32",
        "Tennis" => "Tn43",
    );
    if (isset($sportarray[$searchsport])) {
        header("Location: " . $sportarray[$searchsport] . ".html");
    die;
}

我将如何修改它(我认为这个词正在解析?)以使其区分大小写?例如,我输入“fOoTbAlL”,PHP 会正常引导我到 Fb01.html。

请注意,代码只是一个示例。用户输入的字符串可以包含多个单词,例如“Crazy aWesOme HarpoOOn-Fishing”,如果数组元素“Crazy Awesome Harpoon-Fishing”(注意F破折号前的大写字母),它仍然可以工作。

4

5 回答 5

2

我会使用一个字符串函数,strtolower().

于 2010-05-25T12:41:37.540 回答
2

最简单的方法是使用strtolower将所有内容变为小写以进行比较。

于 2010-05-25T12:42:31.110 回答
2

您可以像这样修改您的代码:

// Searches for values in case-insensitive manner
function in_arrayi($needle, $haystack) {
    return in_array(strtolower($needle), array_map('strtolower', $haystack));
}

$searchsport = $_POST['sport'];
$sportarray = array(
    "Football" => "Fb01",
    "Cricket" => "ck32",
    "Tennis" => "Tn43",
);

if(in_arrayi($searchsport, $sportarray)){
    header("Location: " . $sportarray[$searchsport] . ".html");
    die;
}
于 2010-05-25T12:46:16.513 回答
1
$searchsport = strtolower($_POST['sport']);
$sportarray = array(
    "football" => "Fb01",
    "cricket" => "ck32",
    "tennis" => "Tn43",
);
if (isset($sportarray[$searchsport])){
    header("Location: " . $sportarray[$searchsport] . ".html");
    die;
}

这样,搜索字符串和数组键都是小写的,您可以进行不区分大小写的比较。

如果要保留$sportarray键的大小写,可以执行以下操作:

$searchsport = ucfirst(strtolower($_POST['sport']));
$sportarray = array(
    "Football" => "Fb01",
    "Cricket" => "ck32",
    "Tennis" => "Tn43",
);
if (isset($sportarray[$searchsport])){
    header("Location: " . $sportarray[$searchsport] . ".html");
    die;
}
于 2010-05-25T12:42:16.877 回答
0

<?php
$searchsport = $_POST['sport'];
$sportarray = array(
"Football" => "Fb01",
"Cricket" => "ck32",
"Tennis" => "Tn43",
);
if(isset($sportarray[ucfirst(strtolower($searchsport]))])){
    header("Location: ".$sportarray[$searchsport].".html");
    die;
}
?>

注意ucfirst(strtolower($searchsport]))

LE:添加了 ucfirst

于 2010-05-25T12:44:48.570 回答