Haskella
Haskella

Reputation: 41

PHP making input from web form case insensitive?

So I have some code here that takes user input from a standard web form:

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

How would I go about modifying this (I think the word is parsing?) to make it case insensitive? For example, I type in "fOoTbAlL" and PHP will direct me to Fb01.html normally.

Note that the code is just an example. The string entered by the user can contain more than one word, say "Crazy aWesOme HarpOOn-Fishing", and it would still work if the array element "Crazy Awesome Harpoon-Fishing" (take note of the capital F before the dash).

Upvotes: 1

Views: 2761

Answers (5)

mck89
mck89

Reputation: 19231

$searchsport = strtolower($_POST['sport']);
$sportarray = array(
    "football" => "Fb01",
    "cricket" => "ck32",
    "tennis" => "Tn43",
);
if (isset($sportarray[$searchsport])){
    header("Location: " . $sportarray[$searchsport] . ".html");
    die;
}

In this way the search string and the array keys are both lowercase and you can do a case insensitive comparison.

If you want to preserve the case of the $sportarray keys you can do:

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

Upvotes: 1

David Yell
David Yell

Reputation: 11855

I would use a string function, strtolower().

Upvotes: 2

badideas
badideas

Reputation: 3557

The easiest way is to use strtolower to make everything lowercase to make your comparison.

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382696

You can modify your code like this:

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

Upvotes: 2

Mihai Iorga
Mihai Iorga

Reputation: 39704

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

notice ucfirst(strtolower($searchsport]))?

LE: added ucfirst

Upvotes: 0

Related Questions