Remove Duplicate Data from POST array

Deadly 提交于 2019-12-12 01:05:25

问题


I have been looking for an answer for this, but none seem to actually help my specific situation. I'm trying to post a list of words and then remove the duplicate data (words) that come from the form.

For some reason I can't seem to get array_unique to work. PHP keeps giving me errors saying my post array is a string. But if I try using explode, it says I'm using an array. Really confused right now and very frustrated.

My code is simple:

if(!empty($_POST['keywords']))
{
    $posted = $_POST['keywords'];

    $posted = array_unique($posted);

    echo $posted;
}

I'm not necessarily looking for an exact answer, but some guidance so I can better understand what I'm doing wrong here.

The form:

    <form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
    <p>
        <textarea name="keywords" rows="20" columns="120"></textarea>
    </p>

    <p>
        <input type="submit" name="submit" />
    </p>
</form>

回答1:


Consider first splitting the keywords argument by spaces, then finding the unique values:

$posted = array_unique(explode(' ', str_replace("\n", ' ', $posted)));



回答2:


Maybe you should look into using array_filter

That way you can define your own callback function for maximum rigorousness on your your removes...

http://php.net/manual/en/function.array-filter.php

Also: Have you tried messing around with the array_unique flags?

http://php.net/manual/en/function.array-unique.php




回答3:


Your keywords form field is setup as a textarea, so when you post, you are posting a string. Try this:

$posted = $_POST['keywords'];

$postedKeywords = explode(' ', $posted);

$posted = array_unique($postedKeywords);



回答4:


The previous answers are great, but since the words are being input to a textfield, the delimiter will be unpredictable. Consider using a regular expression instead:

preg_match_all('/([^\s]+)/', $_POST['keywords'], $matches);
$unique_words = array_unique($matches[0]);


来源:https://stackoverflow.com/questions/8514261/remove-duplicate-data-from-post-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!