php搜索并替换html文件中的整个public_html文件夹

时间:2018-08-07 16:16:34

标签: php

使用以下脚本,我们能够在lat long值字符串“ new google.maps.LatLng”的文件中找到副本,并将其粘贴到与Openstreetmap代码相同的文件值中,在该文件值中找到“ locLat ,locLng”。该脚本可以正常运行,但是一次必须完成一个文件。有人可以帮我对整个文件夹(例如public_html文件夹)进行操作吗?

<?php 

$file = 'example.html';
$searchfor = 'new google.maps.LatLng';
$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";

if(preg_match_all($pattern, $contents, $matches)){
//    echo "Found matches:<br />";
//echo implode("<br />", $matches[0]);
$match = implode("<br />", $matches[0]);
$tmpArr = explode('(', $match);
$tmpArr = explode(')', $tmpArr[1]);
$tmpArr = explode(',', $tmpArr[0]);
//print_r($tmpArr);die();
$contents = str_replace("var mymap = L.map('mapid').setView([locLat, locLng], 18);","var mymap = L.map('mapid').setView([".$tmpArr[0].", ".$tmpArr[1]."], 18);",$contents);
$contents = str_replace("var marker = L.marker([palermo],","var marker = L.marker([".$tmpArr[0].", ".$tmpArr[1]."],",$contents);
$contents = str_replace("var marker = L.marker([locLat, locLng],","var marker = L.marker([".$tmpArr[0].", ".$tmpArr[1]."],",$contents);
echo file_put_contents($file,$contents);
}

else{
     echo "No matches found";
fclose ($file); 
 }
?>

2 个答案:

答案 0 :(得分:0)

尝试一下

<?php 
$dir = '/path/to/folder';

if (!file_exists($dir)) throw new Exception("Folder not found", 1);

$files = scandir($dir);
// or following for specific file type
// $files = preg_grep('/.*\.html/', scandir($dir));

foreach ($files as $file) {
    $file = $dir . '/' . $file;
    $searchfor = 'new google.maps.LatLng';
    $contents = file_get_contents($file);
    $pattern = preg_quote($searchfor, '/');
    $pattern = "/^.*$pattern.*\$/m";

    if(preg_match_all($pattern, $contents, $matches)){
//    echo "Found matches:<br />";
//echo implode("<br />", $matches[0]);
        $match = implode("<br />", $matches[0]);
        $tmpArr = explode('(', $match);
        $tmpArr = explode(')', $tmpArr[1]);
        $tmpArr = explode(',', $tmpArr[0]);
//print_r($tmpArr);die();
        $contents = str_replace("var mymap = L.map('mapid').setView([locLat, locLng], 18);","var mymap = L.map('mapid').setView([".$tmpArr[0].", ".$tmpArr[1]."], 18);",$contents);
        $contents = str_replace("var marker = L.marker([palermo],","var marker = L.marker([".$tmpArr[0].", ".$tmpArr[1]."],",$contents);
        $contents = str_replace("var marker = L.marker([locLat, locLng],","var marker = L.marker([".$tmpArr[0].", ".$tmpArr[1]."],",$contents);
        echo file_put_contents($file,$contents);
    }

    else{
        echo "No matches found";
        fclose ($file); 
    }
}
?>

答案 1 :(得分:0)

如果您运行的是Linux,最好使用sed和awk进行此操作

find /home/www/ -type f -exec \ sed -i '' 's/original/replacement/g' {} +