同一个单词在一个字符串中只能使用一次


Same word can only be used once in a string

我的网站上有一个简单的消息功能,今天我开始致力于使发送给多个用户成为可能,这就是我所取得的成就:

到目前为止效果很好,但我刚刚意识到你只是多次输入相同的用户名

那么,如何限制同一单词只出现一次呢? 有这个功能吗? 谷歌搜索"PHP 同一个单词只有一次"和类似的 我找不到太多,但我的英语不是很好

$recipients = 'bob;randomhero;wambamtymam;bill'; // exempel
$recipients_exploded = explode(';', $recipients);
foreach ($recipients_exploded as $recipient) {
    if (empty($recipients)) {
        $error = 'vänligen ange åtminstone en mottagare';
    }
    else if (count($recipients_exploded) > 10) {
        $error = 'du kan endast skicka till 10 stycken användare i ett och samma svep';
    }
    else if (!usernameExist($recipient)) {
        $error = 'det finns ingen användare vid namn '.htmlspecialchars($recipient).'.';
    }
您可以使用

array_unique它会为您提供唯一值。

代码

$recipients_array= explode(';', $recipients);
$unique_recipients_array = array_unique($recipients_array);

解释

您的用户名条目由;字符分隔。因此,首先,您必须使用explode方法分隔每个用户名并形成一个数组。

现在,php有一个名为array_unique的函数。它将接受数组作为输入,并以数组的形式返回唯一元素。因此$unique_recipients_array将仅包含唯一条目