如何检查如果逗号分隔的字符串有重复的值在php


How to check if comma separated strings have duplicate values in php

我有一个包含逗号分隔字符串的变量,我想创建一个检查,如果这个变量内部有重复的字符串,而不将其转换为数组。为了方便起见,每个逗号分隔的字符串有3个字符。

的例子。

$str = 'PTR, PTR, SDP, LTP';

逻辑:如果任何字符串有重复的值,则显示错误。

这应该可以为您工作:

只使用strtok()循环遍历字符串的每个标记,,作为分隔符。然后使用preg_match_all()检查该令牌是否在字符串中不止一次。

<?php
    $str = "PTR, PTR, SDP, LTP";
    $tok = strtok($str, ", ");
    $subStrStart = 0;
    while ($tok !== false) {
        preg_match_all("/'b" . preg_quote($tok, "/") . "'b/", substr($str, $subStrStart), $m);
        if(count($m[0]) >= 2)
            echo $tok . " found more than 1 times, exaclty: " . count($m[0]) . "<br>";
        $subStrStart += strlen($tok);
        $tok = strtok(", ");
    }
?>
输出:

PTR found more than 1 times, exaclty: 2

您将遇到一些问题,只是使用explode。在你的例子中,如果你使用了explosion,你会得到:

'PTR', ' PTR', ' SDP', ' LTP'

你必须在那里映射修剪。

<?php
// explode on , and remove spaces
$myArray = array_map('trim', explode(',', $str));
// get a count of all the values into a new array
$stringCount = array_count_values($myArray);
// sum of all the $stringCount values should equal size of $stringCount IE: they are all 1
$hasDupes = array_sum($stringCount) != count($stringCount);
?>