<?php
error_reporting(E_ALL);
ini_set('display_errors' ,1);
//expression to be found in file name
$find = '.5010.';
//directory name
//we will store renamed files here
$dirname = '5010';
if(!is_dir($dirname))
mkdir($dirname, 0777);
//read all files from a directory
//skip directories
$directory_with_files = './';
$dh = opendir($directory_with_files);
$files = array();
while (false !== ($filename = readdir($dh)))
{
if(in_array($filename, array('.', '..')) || is_dir($filename))
continue;
$files[] = $filename;
}
//iterate collected files
foreach($files as $file)
{
//check if file name is matching $find
if(stripos($file, $find) !== false)
{
//open file
$handle = fopen($file, "r");
if ($handle)
{
//read file, line by line
while (($line = fgets($handle)) !== false)
{
//find REF line
$refid = 'REF*2U*';
if(stripos($line, $refid) !== false)
{
//glue refernce numbers
//check if reference number is not empty
$refnumber = str_replace(array($refid, '~'), array('', ''), $line);
if($refnumber != '')
{
$refnumber = '_'. $refnumber .'_';
$filerenamed = str_replace($find, $refnumber, $file);
copy($file, $dirname . '/' . $filerenamed);
}
echo $refnumber . "\n";
}
}
//close file
fclose($handle);
}
}
}
?>
I have this code, the output should be the replacement of ".5010." with "ref" in the final name, however, when I run the code, it just shows me up to ref not the rest of the file name, I tried it on my computer putty and turns out there's a "?" after the ref number, is there any way I could fix this?
For example; My file is 4867586.5010.476564.ed
After the code executes and reads the file, the output should be: 4867586_SMIL01_476564.ed but instead its: 4867586_SMIL01
And when I checked it out on putty the file name was: 4867586_SMIL01?_476564.ed
The ? in the filename denotes that there's a a non-printable character somewhere in the refnumber line.
This is most likely a line-ending character, or something else.
If it's the former, then that can be solved by changing the line:
$refnumber = str_replace(array($refid, '~'), array('', ''), $line);
to
$refnumber = str_replace(array($refid, '~'), array('', ''), $line);
$refnumber = trim($refnumber); // remove any whitespaces or line endings.
If it's the latter, then you'll need to sanitize your $refnumber variable using one of the file sanitizer functions available online.
Related
I'm currently trying to merge several .csv files with the following code:
<?php $csvdir = get_template_directory() . '/exports';
$csvcontent = '';
if (is_dir($csvdir)) {
if ($handle = opendir($csvdir)) {
while (($file = readdir($handle)) !== false) {
if (substr($file, -4) === ".csv") {
$csvcontent .= file_get_contents($csvdir . $file);
}
}
closedir($handle);
}
}
$result = fopen('app/merge.csv', 'w');
fwrite($result, $csvcontent);
fclose($result); ?>
It's outputting a blank csv file at the moment with no errors. Is there anything obvious wrong with the code?
The template to generate this is in the same directory as the exports folder.
As I have mentioned in the comment, you are missing / after the exports directory name. Hence, the file name is going wrong while reading contents from it.
Also, check the directory is a valid one by echo $csvdir and echo is_dir($csvdir) before the processing starts.
Here is the working demo: https://repl.it/#fiveelements/MergeCSVContents
And here is your modified code:
<?php $csvdir = './exports/';
$csvcontent = '';
if (is_dir($csvdir)) {
if ($handle = opendir($csvdir)) {
while (($file = readdir($handle)) !== false) {
if (substr($file, -4) === ".csv") {
$csvcontent .= file_get_contents($csvdir . $file);
}
}
closedir($handle);
}
}
echo $csvcontent;
$result = fopen('exports/merge.csv', 'w');
fwrite($result, $csvcontent);
fclose($result); ?>
I have a folder in a server with a lot of images and I would like to rename some images. Images that contain (1 example:
112345(1.jpg to 112345.jpg. How can I do this using regex in PHP? I have to mention that my knowledge of PHP is very limited and it's the only language that can effectively do the scripting.
preg_match('/\(1/', $entry) will help you.
Also, you need to pay attention to "what if the file has a duplicate after the rename".
$directory = "/path/to/images";
if ($handle = opendir($directory)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != '.' && $entry != '..') {
// Check "(1"
if (preg_match('/\(1/', $entry)) {
// Rename file
$old = $directory . '/' . $entry;
$new = str_replace('(1', '', $old);
// Check duplicate
if (file_exists($new)) {
$extension = strrpos($new, '.');
$new = substr($new, 0, $extension) . rand() . substr($new, $extension); // Basic rand()
}
rename($old, $new);
}
}
}
closedir($handle);
}
If you want only remove some substring from images names you can do this without regex. Use str_replace function to replace substring to empty string.
As example:
$name = "112345(1.jpg";
$substring = "(1";
$result = str_replace($substring, "", $name);
You can use scandir and preg_grep to filter out the files that needs to be renamed.
$allfiles = scandir("folder"); // replace with folder with jpg files
$filesToRename = preg_grep("/\(1\.jpg/i", $allfiles);
Foreach($filesToRename as $file){
Echo $file . " " . Var_export(rename($file, str_replace("(1.", ".", $file));
}
This is untested code and in theory it should echo the filename and true/false if the rename worked or not.
Only use regex for this if you need to assert the position of the substring, e.g. if you have filenames like Copy (1)(1.23(1.jpg a simple string replacement will go wrong.
$re = '/^(.+)\(1(\.[^\\\\]+)$/';
$subst = '$1$2';
$directory = '/my/root/folder';
if ($handle = opendir($directory )) {
while (false !== ($fileName = readdir($handle))) {
$newName = preg_replace($re, $subst, $fileName);
rename($directory . $fileName, $directory . $newName);
}
closedir($handle);
}
The regular expression used searches for the part before and after the file extension, put the pieces into capturing groups, and glue them together again in the preg_replace without the (1.
I have a folder and have multiple files over there. The file has the below pattern for example.
The file names should be renamed from
file1.mp4.png
file2.flv.png
file3.xxx.png (xxx - can be anything)
to as follows (the last extension remains).
file1.png
file2.png
file3.png
Files having non-png extension should be left untouched.
I am using the logic mentioned in Bulk Rename Files in a Folder - PHP
$handle = opendir("path to directory");
if ($handle) {
while (false !== ($fileName = readdir($handle))) {
$newName = (how to get new filename) // I am struck here
rename($fileName, $newName);
}
closedir($handle);
}
How best I can do this to do a bulk update?
<?php
// Select all PNG Files
$matches = glob("*.[pP][nN][gG]");
// check if we found any results
if ( is_array ( $matches ) ) {
// loop through all files
foreach ( $matches as $filename) {
// rename your files here
$newfilename = current(explode(".", $filename)).".png";
rename($filename, $newfilename);
echo "$filename -> $newfilename";
}
}
?>
try this
$handle = opendir("path to directory");
if ($handle) {
while (false !== ($fileName = readdir($handle))) {
$arr_names = explode(".", $fileName);
$size = sizeof($arr_names);
$ext = $arr_names[$size-1];
if($fileName=="." || $fileName==".." || is_dir($fileName))
{
continue; // skip png
}
if($ext=='png' || $ext=='PNG')
{
$newName = $arr_names[0].".".$ext;
rename($fileName, $newName);
}
}
closedir($handle);
}
Shortest using regex
$handle = opendir("path to directory");
if ($handle) {
while (false !== ($fileName = readdir($handle))) {
$newName = preg_replace("/\.(.*?)\.png$/", '', $fileName); // removes .xxx.png
rename($fileName, ($newName . '.png')); // renames file1.png
}
closedir($handle);
}
I'm trying to make it retrieve the image files on the server but it won't work if there is a space in the name of the image file .. for example there is a space between dead and air , even if I escape it after adding %20, the function returns an empty string .. but if it is a file with no space in the name like 'http://www.m.trialsite.com/images/thumb/Espresso.jpg'; It will work ! .. where am I going wrong ?
$filename = 'http://www.m.trialsite.com/images/thumb/dead air.jpg';
function readfile_chunked($filename,$retbytes=true) {
$chunksize = 1*(1024*1024); // how many bytes per chunk
$buffer = '';
$cnt =0;
// $handle = fopen($filename, 'rb');
$filename = str_replace(' ','%20',$filename);
$handle = fopen($filename, 'rb');
if ($handle === false) {
return false;
}
$filename = str_replace(' ','%20',$filename);
while (!feof($handle)) {
$buffer = fread($handle, $chunksize);
echo $buffer; var_dump($buffer); exit;
ob_flush();
flush();
if ($retbytes) {
$cnt += strlen($buffer);
}
}
$status = fclose($handle);
if ($retbytes && $status) {
return $cnt; // return num. bytes delivered like readfile() does.
}
return $status;
}
use preg_replace("/\s+/","_",$nome); to rename the files and then recovers it it will work
$directory = '/public_html/testfolder/';//example
if ($handle = opendir($directory)) {
while (false !== ($fileName = readdir($handle))) {
$newName = preg_replace("/\s+/","_",$fileName);
rename($directory . $fileName, $directory . $newName);
}
closedir($handle);
}
What if you are doing like this:
$filename = str_replace(' ','%20', 'http://www.m.trialsite.com/images/thumb/dead air.jpg');
myFolderi have thousands of image files that have keyword text for the name. i am trying to read from the list of images and upload the text into a dB field. the problem is that some of the text has utf8 characters like l’Été that show up like this ��t�
how can i read foreign characters so that the accents will insert into the dB field?
this is how im handling it now
function ListFiles($dir) {
if($dh = opendir($dir)) {
$files = Array();
$inner_files = Array();
while($file = readdir($dh)) {
if($file != "." && $file != ".." && $file[0] != '.') {
if(is_dir($dir . "/" . $file)) {
$inner_files = ListFiles($dir . "/" . $file);
if(is_array($inner_files)) $files = array_merge($files, $inner_files);
} else {
array_push($files, $dir . "/" . $file);//$dir = directory name
//array_push($files, $dir);
}
}
}
closedir($dh);
return $files;
}
}
foreach (ListFiles('../../myDirectory') as $key=>$file){
//$file = preg_replace( '#[^\0-\x80]#u',"", $file );
echo $file ."<br />";
}
this is producing the same result
$str = "l’Été";
utf8_decode($str);
echo $str;
This solution may work for you, it will loop through all files in a directoy and then recursivly through any directories found until it ends up with a massive array of files.
Ive added some points you may wish to change, eg either mutli or single dimension arrays ( all depend on if you may want to maintain the folder structure.
and also if you want the file extention to be saved when you save the file name to db.
Code
function recursive_search_dir($dir) {
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (in_array($file,array(".","..")))
continue; // We dont want to do anything with parent / current directory.
if (is_dir($file)) {
$result[] = recursive_search_dir($file); // Multi-dimension
# OR
array_merge($result,recursive_search_dir($file));// Single-dimension if you dont care about folder structure.
} else {
$result[] = utf8_decode($file); // full file name ( includes extention )
# OR
$result[] = utf8_decode(filename($file,PATHINFO_FILENAME)); // if you only want to capture the name and not the extention.
}
}
closedir($handle);
}
return $result;
}
$files = recursive_search_dir("."); // recursively searcht the current directory.