Jump to content

Using an array to restrict search


9999

Recommended Posts

This is a snipet of code I have.  I eventually may want to increase this list to 10 words.  What am  I doing wong?

[code]$search = $_GET['search'];

$not_allowed = array('and', 'or', 'of', 'is', 'the');


if (stristr($search, $not_allowed))
        {
            echo 'Your search contains a word that is not allowed';
        }[/code]
Link to comment
Share on other sites

Try this:
[code]
<?php
$word_filter = array(
'and',
'or',
'of',
'is',
'the',
);

$search = $_GET['search'];

function has_bad_words($search)
{
global $word_filter;

$split = preg_split("#\s+#", $search, -1, PREG_SPLIT_NO_EMPTY);

if (is_array($split))
{
foreach ($split as $search_word)
{
if (in_array($search_word, $word_filter))
{
return true;
}
}
}

return false;
}

if (has_bad_words($search))
{
echo "Your search contains a word that is not allowed";
}
else
{
echo "success";
}
?>
[/code]
Link to comment
Share on other sites

or a simpler way is this.

[code=php:0]
$search = $_GET['search'];
$list = array('and', 'or', 'of', 'is', 'the');
foreach($list as $banned) {
  $match = strpos($search, $banned);
}
if ($match !== false) {
    echo "Your search contains banned words";
}
//continue your search
[/code]

Hope this helps,
Tom
Link to comment
Share on other sites

Thanks guys for your help.  I was still wondering if there is anything I can do with my existig code to make it work; particularly this line [code]if (stristr($search, $not_allowed))[/code] as I already have a complicated maze of nested loops and such.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.