【问题标题】:Replacing keywords in a PHP script file using PHP使用 PHP 替换 PHP 脚本文件中的关键字
【发布时间】:2010-11-19 20:45:58
【问题描述】:

我有一个混合了 html、文本和 php 的 PHP 文件,包括名称 areaname-house.php。文件的 text/html 部分在不同的地方包含字符串“areaname”。另一方面,我有一个带有城市名称的字符串数组。

我需要一个 PHP 脚本,它可以获取每个字符串(来自字符串数组),复制 areaname-house.php 并创建一个名为 arrayitem-house.php 的新文件,然后在新创建的文件中,替换字符串“areaname " 与数组项。我已经能够在以下代码中使用示例变量(城市名称)作为测试成功地创建克隆文件的第一部分:

    <?php
    $cityname = "acton";
    $newfile = $cityname . "-house.php";
    $file = "areaname-house.php";

    if (!copy($file, $newfile)) {
        echo "failed to copy $file...n";

    }else{

        // open the $newfile and replace the string areaname with $cityname

    }

?>

【问题讨论】:

    标签: php file replace clone keyword


    【解决方案1】:
    $content = file_get_contents($newfile);
    $content = str_replace('areaname', $cityname, $content);
    file_put_contents($newfile, $content);
    

    更简单的是......

    $content = file_get_contents($file); //read areaname-house.php
    $content = str_replace('areaname', $cityname, $content);
    file_put_contents($newfile, $content); //save acton-house.php
    

    因此您不需要显式复制文件。

    【讨论】:

      猜你喜欢
      • 2013-09-30
      • 2012-08-07
      • 2019-11-04
      • 2014-10-07
      • 2011-02-14
      • 2014-07-11
      • 2013-03-22
      • 2017-08-01
      • 2013-10-09
      相关资源
      最近更新 更多