如何从名称列表创建多个 TXT/PHP 文件


how to create multiple txt/php files from a list of names?

我有一个文本文件叫做newsites.txt里面有一堆我想用来创建一个新的wp-config.php文件(wordpress文件)的名字。

新网站的内容.txt

    UserName:DatabaseName:DatabasePassword
    UserName2:DatabaseName2:DatabasePassword2

WP配置的内容.php

    /** The name of the database for WordPress */
    define('DB_NAME', 'database_name_here');
    /** MySQL database username */
    define('DB_USER', 'username_here');
    /** MySQL database password */
    define('DB_PASSWORD', 'password_here');

我只需要替换 wp-config 中的这 3 个字段.php并将其另存为 UserName-wp-config.php然后遍历列表的其余部分。

有什么想法我可以用来自动化吗?我尝试寻找批处理脚本,但不知道如何在 php 文件中执行"查找和替换"代码。谢谢

你可以用一个简单的PHP脚本来做到这一点:

<?
$template = file_get_contents("wp-config.php");
$arrSearch = [ "database_name_here", "username_here", "password_here" ];
$content = file_get_contents("newsites.txt");
$arrLines = explode("'n", str_replace("'r'n", "'n", $content));
foreach ($arrLines as $line) {
    $arrLine = explode(":", $line);
    $userName = $arrLine[0];
    $dbName = $arrLine[1];
    $password = $arrLine[2];
    $arrReplace = [ $dbName, $userName, $password ];
    $new = str_replace($arrSearch, $arrReplace, $template);
    $filename = "{$userName}-wp-config.php";
    file_put_contents($filename, $new);
}

你能修改 wp-config.php 文件吗?如果是这样,那么您可以使用一个有趣的技巧,以非常简单的方式解决此问题。在这个问题中,您使用 wp-config.php 作为模板,并希望在某些给定位置替换文本。诀窍在于将 Batch 变量的名称放在那些地方,并启用延迟扩展;例如:

/** The name of the database for WordPress */
define('DB_NAME', '!database_name_here!');
/** MySQL database username */
define('DB_USER', '!username_here!');
/** MySQL database password */
define('DB_PASSWORD', '!password_here!');

这样,当显示文件的行时,每个!variable_name!将自动替换为变量的值!此方法避免显式查找每个字符串并通过每个替换值更改它。

@echo off
setlocal EnableDelayedExpansion
rem Process all lines in newsites.txt
for /F "tokens=1-3 delims=:" %%a in (newsites.txt) do (
   rem Assign values for the corresponding variables
   set "username_here=%%a"
   set "database_name_here=%%b"
   set "password_here=%%c"
   rem Using the values of previous variables
   rem just read and write the lines in wp-config.php;
   rem the variables will be replaced by their values because Delayed Expansion
   (for /F "delims=" %%d in (wp-config.php) do (
      echo %%d
   )) > "!username_here!-wp-config.php"
   echo "!username_here!-wp-config.php" file created
)

输出示例:

C:'> test.bat
"UserName-wp-config.php" file created
"UserName2-wp-config.php" file created
C:'> type UserName-wp-config.php
/** The name of the database for WordPress */
define('DB_NAME', 'DatabaseName');
/** MySQL database username */
define('DB_USER', 'UserName');
/** MySQL database password */
define('DB_PASSWORD', 'DatabasePassword');
C:'> type UserName2-wp-config.php
/** The name of the database for WordPress */
define('DB_NAME', 'DatabaseName2');
/** MySQL database username */
define('DB_USER', 'UserName2');
/** MySQL database password */
define('DB_PASSWORD', 'DatabasePassword2');