delete duplicate and original string php

时间:2018-03-09 19:07:23

标签: php arrays duplicates

i want to delete duplicate string and original duplicate! for example:

my string = one two three one two
and i want = three

my code:

<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>
<?php
if(!empty($_POST['keywords']))
{
$posted = $_POST['keywords'];

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

echo print_r($posted, true);
}


?>

please Help me Thanks

2 个答案:

答案 0 :(得分:0)

After you explode your string to words - count all values in array:

$posted = explode(' ', str_replace("\r\n", ' ', $posted));
$counted_values = array_count_values($posted);
// then filter by value, if value equals 1 - echo it, or do whatever you want
foreach ($counted_values as $k => $v) {
    if ($v == 1) {
        echo $k;
    }
}

答案 1 :(得分:0)

Similar to the other answer but using array_filter:

$posted = array_filter(array_count_values(str_replace("\r\n", ' ', $posted)), 
                       function($v) { return $v === 1; });