PHP代码中仅替换{name}标签内短横线为空格的问题求助
解决PHP中仅替换{name}标签内容的短横线转空格问题
你的代码当前会全局替换文件内容里的所有短横线为空格,这是因为最后一步对整个文件内容执行了短横线替换和首字母大写操作。要实现仅对{name}替换后的内容处理短横线,需要先处理提取出的名称变量,再将处理后的结果替换到文件中。
修正后的代码如下:
<?php error_reporting(E_ALL); ini_set('display_errors', 1); $folderPath = 'folder location'; // 替换为你的实际文件夹路径 $files = scandir($folderPath); foreach ($files as $file) { if (pathinfo($file, PATHINFO_EXTENSION) === 'html') { $filePath = $folderPath . '/' . $file; // 获取不带扩展名的文件名 $fileName = pathinfo($file, PATHINFO_FILENAME); // 提取-team-work之前的部分 $name = str_replace('-team-work', '', $fileName); // 仅对提取出的名称做短横线转空格+首字母大写处理 $formattedName = ucwords(str_replace('-', ' ', $name)); // 读取文件内容 $fileContent = file_get_contents($filePath); // 直接用处理好的名称替换{name}标签 $updatedContent = str_replace('{name}', $formattedName, $fileContent); // 将更新后的内容写回文件 if (file_put_contents($filePath, $updatedContent) !== false) { echo "Successfully updated $file<br>"; } else { echo "Failed to update $file<br>"; } } } ?>
关键修改点:
- 把对短横线的替换和首字母大写操作,从全局文件内容转移到提取出的$name变量上,生成格式化后的
$formattedName - 用处理好的
$formattedName直接替换文件中的{name}标签,这样只会修改标签对应的内容,文件里其他地方的短横线不会被改动
内容的提问来源于stack exchange,提问作者rony sen
相关产品推荐
相关产品推荐

