Home  >  Article  >  Backend Development  >  How to modify constants in php

How to modify constants in php

王林
王林Original
2020-07-23 18:02:373978browse

How to modify constants in php: You can use regular expressions to modify constants. To use regular expressions, we need to use the preg_replace() function, which is used to perform a regular expression search and replacement.

How to modify constants in php

#We can use regular replacement to modify constants, which is the simplest and most convenient.

(Recommended tutorial: php tutorial)

Function introduction:

preg_replace function performs a regular expression search and replacement.

Function syntax:

mixed preg_replace(mixed $pattern , mixed $replacement, mixed $subject[, int $limit = -1[, int &$count]])

Parameter description:

  • $pattern: The pattern to be searched, which can be a string or a string array.

  • $replacement: String or array of strings used for replacement.

  • $subject: The target string or string array to be searched and replaced.

  • $limit: Optional, the maximum number of substitutions for each subject string per pattern. The default is -1 (no limit).

  • $count: Optional, the number of times the replacement is performed.

Return value:

If subject is an array, preg_replace() returns an array, otherwise it returns a string. If a match is found, the replaced subject is returned, otherwise the unchanged subject is returned. If an error occurs, NULL is returned.

Code implementation:

/*
    @param 常量文件
    @param 修改数组(常量名=>常量值)
    @return 失败返回false  成功修改常量文件
    */
    function constEdit($file, $arr)
    {
        $info = file_get_contents($file);
        foreach ($arr as $k => $v) {
            $info = preg_replace("/define\(\"{$k}\",\".*?\"\)/", "define(\"{$k}\",\"{$v}\")", $info);
        }
        return file_put_contents($file, $info);
    }

Using this method we only need to pass in the corresponding constant file location and modified array.

Application scenario:

<form action="action.php" method="post">
    <input name="HOST" type="text" />
    <input name="DBNAME" type="text" />
    <input type="submit" value="修改"/>
</form>

At this time, in the action.php page, you only need to receive the complete array of $_POST and pass it into the method.

It should be noted that you need to use double quotes when defining constants, such as:

define("HOST","127.0.0.1");
define("DBNAME","mysql");

Secondly, the name of the constant should correspond to the name in the form.

The above is the detailed content of How to modify constants in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn