fopen()
是 PHP 中用于打开文件或 URL 的函数,它创建一个文件指针资源,用于后续的文件读写操作。
$handle = fopen(string $filename, string $mode, bool $use_include_path = false, resource $context = null)
| 模式 | 描述 | |------|------| | 'r' | 只读方式打开,文件指针指向文件头 | | 'r+' | 读写方式打开,文件指针指向文件头 | | 'w' | 只写方式打开,文件指针指向文件头并清空文件内容;如果文件不存在则创建 | | 'w+' | 读写方式打开,文件指针指向文件头并清空文件内容;如果文件不存在则创建 | | 'a' | 追加方式打开,文件指针指向文件末尾;如果文件不存在则创建 | | 'a+' | 读写方式打开,文件指针指向文件末尾;如果文件不存在则创建 | | 'x' | 创建并以只写方式打开,如果文件已存在则返回 FALSE | | 'x+' | 创建并以读写方式打开,如果文件已存在则返回 FALSE |
// 读取文件
$file = fopen("example.txt", "r") or die("无法打开文件!");
while(!feof($file)) {
echo fgets($file)."<br>";
}
fclose($file);
// 写入文件
$file = fopen("newfile.txt", "w") or die("无法打开文件!");
$txt = "Hello World\n";
fwrite($file, $txt);
fclose($file);
file_exists()
或处理错误fclose()
释放资源str_replace()
是 PHP 中用于字符串替换的函数,可以替换字符串中的某些字符或子串。
mixed str_replace(mixed $search, mixed $replace, mixed $subject, int &$count = null)
$search
:要查找的值(可以是字符串或数组)$replace
:替换的值(可以是字符串或数组)$subject
:被搜索的字符串或数组$count
(可选):如果指定,将被设置为替换发生的次数// 简单替换
$str = "Hello world!";
echo str_replace("world", "PHP", $str); // 输出: Hello PHP!
// 数组替换
$search = array("Hello", "world");
$replace = array("Hi", "PHP");
echo str_replace($search, $replace, "Hello world!"); // 输出: Hi PHP!
// 统计替换次数
$count = 0;
str_replace("l", "L", "Hello world!", $count);
echo $count; // 输出: 3
str_ireplace()
// 读取文件内容并替换特定字符串
$filename = "template.html";
$file = fopen($filename, "r") or die("无法打开文件!");
$content = fread($file, filesize($filename));
fclose($file);
// 替换模板变量
$replacements = array(
"{TITLE}" => "我的网页",
"{CONTENT}" => "这是主要内容区域",
"{FOOTER}" => "版权所有 © 2023"
);
$newContent = str_replace(array_keys($replacements), array_values($replacements), $content);
// 写入新文件
$newFile = fopen("output.html", "w") or die("无法创建文件!");
fwrite($newFile, $newContent);
fclose($newFile);
fopen()
时,避免使用用户提供的路径直接打开文件htmlspecialchars()
防止 XSS 攻击