douqianxun8540 2014-07-25 13:13
浏览 13
已采纳

如何从文件中更改变量的值?

I need to replace a line in a file.php.

I need to replace a value of a variable of a file.php, yet I can get the desired line, take the value of the variable but do not know how to replace the whole line.

Example:

<?php

    $archive = file('Library/config/PaymentConfig.php'); // transforms the content into an array where each line is a position
    $valueLine = $archive[10]; // $environment = 'production';

    function getEnvironment($valueLine){
        $removecharacters = array('$environment = ', "'", ';');
        return str_replace($removecharacters, '', urldecode($valueLine)); // returns only the value of the variable
    }

    if (getEnvironment($valueLine) == $myValue) { // $myValue = production or sandbox   
        // Here I need to replace the line
        // For $environment = 'production'; or $environment = 'sandbox';
    }

?>
  • 写回答

3条回答 默认 最新

  • dongtaihui5131 2014-07-25 19:05
    关注

    Correct answer 2

    <?php
        $archive = "Library/config/PaymentConfig.php";
        $search = "PaymentConfig['environment']";
        $arrayArchive = file($archive);
        $position = 0;
    
        for($i = 0; $i < sizeof($arrayArchive); $i++){      
            if(strpos($arrayArchive[$i],$search) && (strpos($arrayArchive[$i],'production') || strpos($arrayArchive[$i],'sandbox'))){
                $fullLine = $arrayArchive[$i]; // $PaymentConfig['environment'] = "production"; // production, sandbox
                $position = $i;     
    
                if(strpos($fullLine, '"production"') == true){
                    $environment = '"production"';
                } else if(strpos($fullLine, '"sandbox"') == true){
                    $environment = '"sandbox"';
                }
            }
        }
    
        echo $environment; // current environment
        $newEnvironment = '"sandbox"'; // or $newEnvironment = '"production"';
    
        if ($environment == $myValue) { // $myValue = production or sandbox  
            $arrayArchive[$position] = str_replace($environment, $newEnvironment, $fullLine);
            file_put_contents($archive, implode("", $arrayArchive));    
        }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 eclipse连接sap后代码跑出来空白
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案