简体   繁体   English

使用PHP递归搜索目录中的文件并更改值

[英]Use PHP to search directorys for files recursively and change values

I have some php that's replacing color values in css files in a directory.我有一些 php 正在替换目录中 css 文件中的颜色值。 It works fine except that it only searches for css files in the main directory.它工作正常,只是它只在主目录中搜索 css 文件。 I've been searching but cant seem to find a simple way to make this recursive.我一直在寻找,但似乎无法找到一种简单的方法来进行递归。 Any ideas?有任何想法吗?

I'm currently using $arr=glob("themes/Evolution/*.css");我目前正在使用 $arr=glob("themes/Evolution/*.css");

An example folder structure with css files are.带有 css 文件的示例文件夹结构是。

Main Dir > Style.css
Main Dir > Folder 1 > mycss.css
Main Dir > Folder 2 > mycss.css
Main Dir > Folder 3 > mycss.css

 //Read default color from INI $lines_array = file("modules/evolution/evolution.ini"); $search_string = "currentcolor"; foreach($lines_array as $line) { if(strpos($line, $search_string) !== false) { list(, $new_str) = explode("=", $line); $new_str = trim($new_str); //This line removes the spaces before and after. } } $inicurrentcolor = $new_str; //code to change css color if(isset($_REQUEST['resetcolor'])){ $arr=glob("themes/Evolution/*.css"); //your css file's path $textboxdefaultcolorcode=$_POST['defaultcolor']; foreach($arr as $key=>$val){ $str=file_get_contents($val); $str=str_replace($inicurrentcolor, $textboxdefaultcolorcode, $str); file_put_contents($val, $str); } } <div class="colorbox"> <br> <label id="steps">Reset Evolution theme color back to the default color.</label> <br> <br> <Form name="default1" method="POST" action="home.php?m=evolution"> <label for="color1">Default Theme Color: </label><input style="background-color:#379BB9; color:#ffffff" type="text" id="defaultcolor" name="defaultcolor" value="#379BB9" readonly> <br> <br> <input type="submit" name="resetcolor" value="Reset Theme Color"> </form> <br> </div>

I figured out the answer with some help.我在一些帮助下找到了答案。 The code below will allow you to search recursively with the code above.下面的代码将允许您使用上面的代码进行递归搜索。 Hope this helps.希望这可以帮助。

 $themedir = 'themes/Evolution'; $allFiles = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($themedir)); $cssFiles = new RegexIterator($allFiles, '/\\.css$/i'); if(isset($_REQUEST['resetcolor'])){ $textboxdefaultcolorcode=$_POST['defaultcolor']; //added line foreach($cssFiles as $cssFile=>$val){ $str=file_get_contents($val); $str=str_replace($inicurrentcolor, $textboxdefaultcolorcode, $str); file_put_contents($val, $str); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM