PHP替换文件中的字符而不打开文件

时间:2015-05-06 09:09:38

标签: php replace str-replace file-writing

我有一个文件,其中包含:
file content NULNULNULNUL something else
当我尝试获取文件内容时 $str = file_get_contents($fileName)中的$str仅显示file content 如何在没有打开文件的情况下替换文件中的NUL?

2 个答案:

答案 0 :(得分:0)

1。)将替换的内容作为字符串。首先像你一样获取文件内容。

$str = file_get_contents($fileName)

然后将所有出现的NUL替换为空格,如:

$new_content =  str_replace('NUL'," ",$str);  

2.。)替换文件内的内容(替换内容并将其写回文件):

file_put_contents($fileName,str_replace('NUL',' ',file_get_contents($fileName)));  

这里我们使用file_put_contents - 将字符串写入文件。我们将filenamereplaced-string作为参数传递

答案 1 :(得分:-1)

我将每个字符转换为assci代码。这是现在的工作:

$newStr='';
$str = file_get_contents($fileName);
$length = strlen($str);

for ($i=0; $i < $length; $i++)
{
    $current = ord($str{$i});
    if ($current != 0x0)
    {
        $newStr .= chr($current);
    }
    else
    {
        $newStr .= "";
    }
}
$num = file_put_contents($fileName,$newStr);
相关问题