遍历字符串以查找丢失的数字不起作用

Iterating through string to find missing numbers not working

下面的代码应该打印,2,6,7,8 - 至少我想要它到。我到底错过了什么?目的是在一个长数字中找到缺失的数字。

$x = 1;
$missing = "";
$newfname = "193555415493359"; 
while($x <= 9) {
    $pos = strpos($newfname,$x);
    if($pos === false) {        
        $missing .= ",$x";                  
    }
    $x++;
} 
echo $missing;

根据the function documentation,"If needle is not a string, it is converted to an integer and applied as the ordinal value of a character."换句话说,如果你传递给它9,它正在寻找制表符(ASCII 9.)

试试这个:

$x = 1;
$missing = "";
$newfname = "193555415493359"; 
while($x <= 9) {
    $pos = strpos($newfname, (string)$x);
    if($pos === false) {        
        $missing .= ",$x";                  
    }
    $x++;
} 
echo $missing;

唯一的变化是 cast $x 作为搜索字符串。

不过,这可以更有效地完成:

$haystack = "193555415493359";
$needles = "123456789";
$missing = array_diff(str_split($needles), str_split($haystack));
echo implode(",", $missing);