使用 str_replace() 函数替换文件后缀:创建一个包含要替换和新后缀的数组。使用 str_replace() 函数将文件路径中的旧后缀替换为新后缀。
如何使用 PHP 数组替换文件后缀
答案:使用 str_replace() 函数。
详细步骤:
- 创建一个数组,其中包含要替换的后缀和新的后缀。例如:
$old_suffixes = ['txt', 'html', 'php'];
$new_suffixes = ['md', 'htm', 'phtml'];
- 使用 str_replace() 函数,将文件路径中的旧后缀替换为新后缀。语法如下:
$new_file_path = str_replace($old_suffixes, $new_suffixes, $file_path);
其中:
立即学习“PHP免费学习笔记(深入)”;
- $file_path 是要替换后缀的文件路径。
- $old_suffixes 是旧后缀的数组。
- $new_suffixes 是新后缀的数组。
- $new_file_path 是替换后缀后的新文件路径。
示例代码:
<?php $file_path = 'index.php';
$old_suffixes = ['txt', 'html', 'php'];
$new_suffixes = ['md', 'htm', 'phtml'];
$new_file_path = str_replace($old_suffixes, $new_suffixes, $file_path);
echo $new_file_path; // 输出:index.phtml