PHP按关键字过滤

时间:2016-11-23 22:21:22

标签: php filter keyword

好的,所以我目前所有的代码都是通过一个关键字进行过滤,但我想要过滤100多个关键字。我没有足够的PHP经验,我已经尝试过并且失败了。

这是我当前的代码,但我想修改它以使用多个关键字。

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

如果有人能帮我解决这个改变,我将不胜感激:)

1 个答案:

答案 0 :(得分:1)

我建议使用stripos()代替strpos()。与strpos()不同,stripos()不区分大小写。将关键字视为数组。我们假设它们是逗号分隔的:

<?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>