Dzje Dzje - 11 days ago 7
PHP Question

PHP Filter By Keyword

Okay so I currently have the code all done to filter by one keyword but I'm wanting to filter by 100+ keywords. I'm not experienced in PHP enough I've tried and failed.

Here is my current code but I'm wanting to modify it to use multiple keywords.

function postResolve ($key) {
return isset($_POST[$key]) ? $_POST[$key] : null;
}

$formData = [
'keyword' => postResolve('keyword'),
'text' => postResolve('text')
];

if (is_null($formData['keyword']) || is_null($formData['text'])) {
return 'Nothing to do... Missing text or keyword.';
}

$text = explode(PHP_EOL, $formData['text']);

$storage = [];

foreach ($text as $sentence) {
if (strpos($sentence, $formData['keyword']) !== false) {
$storage[] = trim($sentence);
}
}

echo json_encode($storage);


Would appreciate if someone could give me a hand on this change :)

Answer

I would suggest using stripos() instead of strpos(). Unlike the strpos(), stripos() is case-insensitive. Treat your keywords as an array. Let's assume they are comma-delimited:

<?php
    function postResolve ($key) {
        return isset($_POST[$key]) ? $_POST[$key] : NULL;
    }

    function checkKeywords($sentence, $keywords) {
        foreach($keywords as $keyword) {
            if(stripos($sentence, $keyword) !== FALSE) { return TRUE; }
        }
        return FALSE;
    }

    if(isset($_POST) && !empty($_POST)) {

        $formData = array(
            'keywords' => postResolve('keywords'),
            'text'    => postResolve('text')
        );

        if(is_null($formData['keywords']) || is_null($formData['text'])) {
            echo 'Nothing to do... Missing text or keyword.';
        }

        $text = explode(PHP_EOL, $formData['text']);
        $keywords = explode(',', $formData['keywords']);

        $storage = array();

        foreach($text as $sentence) {
            if(checkKeywords($sentence, $keywords)) {
                $storage[] = trim($sentence);
            }
        }

        echo json_encode($storage);
        exit();
    }
?>

<form>
    <textarea name="keywords"></textarea>
    <textarea name="text"></textarea>
    <input type="submit" value="Submit">
</form>
<div></div>

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
    $('form').on('submit', function(event) {
        event.preventDefault();
        $('div').load(location.href, $('form').serializeArray());
    });
</script>
Comments