gpt4 book ai didi

php - 通过提示输入 php 中的第一个数字来顺序编号文件

转载 作者:可可西里 更新时间:2023-11-01 11:46:15 38 4
gpt4 key购买 nike

php、命令行、windows。

我需要对目录中的每个 .txt 文件按顺序编号。当我键入脚本时,有什么方法可以在命令行的序列中指定要使用的第一个数字? (而不是每次都手动编辑脚本本身)。

或者(甚至更好)被提示输入第一个数字两次(用于确认)?

例如,在命令行中(“285603”只是一个示例数字):

c:\a\b\currentworkingdir>php c:\scripts\number.php 285603

或者(甚至更好)

c:\a\b\currentworkingdir>php c:\scripts\number.php
c:\a\b\currentworkingdir>Enter first number:
c:\a\b\currentworkingdir>Re-enter first number:

编号脚本:

<?php
$dir = opendir('.');
// i want to enter this number OR being prompted for it to enter twice in the command line
$i = 285603;
while (false !== ($file = readdir($dir)))
{
if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'txt')
{
$newName = $i . '.txt';
rename($file, $newName);
$i++;
}
}
closedir($dir);
?>

有什么提示吗?

最佳答案

您应该使用 $argv 变量。它是一个数组,第一个元素指示脚本文件名,下一个元素是传递的参数。如果您在控制台中键入 php script.php 1234$argv 变量如下所示:

array(4) {
[0]=>
string(10) "script.php"
[1]=>
string(4) "1234"
}

编辑:您的代码应如下所示:

<?php
# CONFIRMATION
echo 'Are you sure you want to do this [y/N]';
$confirmation = trim(fgets( STDIN));
if ($confirmation !== 'y') {
exit (0);
}

$dir = opendir('.');
$i = $argv[1];
while (false !== ($file = readdir($dir)))
{
if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'txt')
{
$newName = $i . '.txt';
rename($file, $newName);
$i++;
}
}
closedir($dir);
?>

关于php - 通过提示输入 php 中的第一个数字来顺序编号文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44048013/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com