在PHP中删除字符串中的NULL字符

时间:2014-03-24 06:09:43

标签: php regex

我在php中有代码从文件读取数据但是当我打印原始和唯一的单词时,NULL字符包含在其中。那么我怎么能删除它们。我也使用了修剪和字符串替换功能,但没有成果。以下是插图的代码。

$string = "A quick and the brown fox jumps over the lazy dog";
$words = explode(" ",$string);
$unique = array_unique($words);

for ($a=0;$a<=count($unique);$a++) {
    if ($unique[$a] == NULL) {
        echo "NULL";
    }
    echo $unique[$a]." ";
}
echo "<br>";

for ($b=0;$b<=count($words);$b++) {
    if ($words[$b] == NULL) {
        echo "NULL";
    }
    echo $words[$b]." ";
}

此代码以字符串显示,并在每个循环中打印一个NULL字符。但是当我读取文件时,每个循环中都有多个NULL字符。请帮帮我。感谢。

2 个答案:

答案 0 :(得分:1)

您需要添加此

$unique = array_values(array_unique($words)); 

这是因为array_unique保留了索引,您将遇到Undefined Offset通知。

另外,将for循环的条件更改为<而不是<=

修改后的代码..

<?php

$string = "A quick and the brown fox jumps over the lazy dog";
$words = explode(" ",$string);
$unique = array_values(array_unique($words)); //<--- You really need to do this !

for ($a=0;$a<count($unique);$a++) { //<--- Changed the operator
    if ($unique[$a] == NULL) {
        echo "NULL";
    }
    echo $unique[$a]." ";
}
echo "<br>";

for ($b=0;$b<count($words);$b++) { //<--- Changed the operator
    if ($words[$b] == NULL) {
        echo "NULL";
    }
    echo $words[$b]." ";
}

使用foreach - &gt;由Jack

提出
<?php

$string = "A quick and the brown fox jumps over the lazy dog";
$words = explode(" ",$string);
$unique = array_unique($words);

foreach($unique as $k=>$v) {
    if ($unique[$k] == NULL) {
        echo "NULL";
    }
    echo $unique[$k]." ";
}
echo "<br>";

foreach ($words as $k=>$v) {
    if ($words[$k] == NULL) {
        echo "NULL";
    }
    echo $words[$k]." ";
}

答案 1 :(得分:0)

您不想要str_replace("\0","null",$string)甚至str_replace("\0","",$string)