Renaming Alphanumeric images with PHP - php

I have almost 10,000 images in a Folder with image name like
Abies_koreana_Blauer_Pfiff_05-06-10_1.jpg
Abies_koreana_Prostrate_Beauty_05-05-10_2.jpg
Chamaecyparis_obtusa_Limerick 06-10-10_3.jpg
Fagus_sylvatica_Dawyck_Gold_05-02-10_1.jpg
What i want do is rename the images using PHP so that only the characters remain in the image name want to delete the Numeric part so for example the above images would look like
Abies_koreana_Blauer_Pfiff.jpg
Abies_koreana_Prostrate_Beauty.jpg
Chamaecyparis_obtusa_Limerick.jpg
Fagus_sylvatica_Dawyck_Gold.jpg
Is this possible ? Or i have to do it manually ?

foreach file name do this
$new_filename = preg_replace("/(\w\d{0,2}[\W]{1}.+\.)/",".",$current_file_name);
so final function may look like this
function renameFiles($directory)
{
$handler = opendir($directory);
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
if(preg_match("/(\w\d{0,2}[\W]{1}.+\.)/",$file)) {
echo $file."<br/>";
}
rename($directory."/".$file,$directory."/".preg_replace("/(\w\d{0,2}[\W]{1}.+\.)/",".",$file));
}
}
closedir($handler);
}
renameFiles("c:/wserver");
Updated

You can do this with PHP (or bash).
Your friends are RecursiveDirectoryIterator to walk through directories, preg_replace() to modify the file names, rename() to reflect changed filename on disk.
What you're trying to do can be done in ~10 lines of code. Using the ingredients above, you should be able to write a little script to change filenames yourself.
Update
throwing out the numeric parts (according to the examples given) can be done with a rather simple regular expression. Note that this will remove any numbers (-_ ) between the [a-z] filename and the suffix (".jpq"). So you won't get "foo3.png" but "foo.png". If this is a problem, the regex can be adjusted to meet that criteria…
<?php
$files = array(
'Abies_koreana_Blauer_Pfiff_05-06-10_1.jpg',
'Abies_koreana_Prostrate_Beauty_05-05-10_2.jpg',
'Chamaecyparis_obtusa_Limerick 06-10-10_3.jpg',
'Fagus_sylvatica_Dawyck_Gold_05-02-10_1.jpg',
);
foreach ($files as $source) {
// strip all numeric (date, counts, whatever)
// characters before the file's suffix
// (?= …) is a non-capturing look-ahead assertion
// see http://php.net/manual/en/regexp.reference.assertions.php for more info
$destination = preg_replace('#[ _0-9-]+(?=\.[a-z]+$)#i', '', $source);
echo "'$source' to '$destination'\n";
}

Related

How can I check if a file exists with a certain string in its filename?

I'd like to be able to search a directory for a file that starts with a specific string, for example:
- foo
- 1_foo.jpg
- 2_bar.png
How would I check directory foo for files that begin with "1_"?
I've tried using file_exists and preg_match like so:
if (file_exists("foo/" . preg_match("/^1_/", "foo/*"))) echo "File exists.";
but this doesn't work.
Sounds like you need the glob() function. The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.
<?php
foreach (glob('1_*.*') as $filename) {
echo "$filename\n";
}
?>
The above example will output something similar to:
1_foo.png
1_bar.png
1_something.png
Sorry, but the filesystem doesn't understand wildcards or regular expressions. To accomplish what you want, you have to open the directory and read its contents, getting a list of all the files in that directory. Then you use standard string utilities to see which filenames match your criteria.
I think PHP's scandir is what you want as a starting point. You can also use glob but that actually forks a shell to get the file list (which in turn will do the C equivalent of scandir()).
You can use the glob() function
<?php
$list = glob('1_*.*');
var_dump($list);
I was having some trouble checking a directory and files and I gather some scripts here and there and this worked for me (Hope it helps u too):
if ($handle = opendir('path/to/folder/'))
{
while ( false !== ($entry = readdir($handle)) ) {
if ( $entry != "." && $entry != ".." ) {
// echo "$entry<br>";
if (preg_match("/^filename[0-9]_[0-9].jpg/", $entry))
{
// $found_it = TRUE;
}
}
}
closedir($handle);
}

Get full path from filename in php

So I have a URL which contains &title=blabla
I know how to extract the title, and return it. But I've been searching my ass off to get the full path to the filename when I only have the filename.
So what I must have is an way to search in all directories for an html file called 'blabla' when the only thing it has is blabla. After finding it, it must return the full path.
Anyone who does have an solution for me?
<?php
$file = $_GET['title'];
if ($title = '') {
echo "information.html";
} else {
//here it must search for the filepath and echo it.
echo "$filepath";
}
?>
You can use the solution provided here.
It allows you to recurse through a directory and list all files in the directory and sub-directories. You can then compare to see if it matches the files you are looking for.
$root = '/'; // directory from where to start search
$toSearch = 'file.blah'; // basename of the file you wish to search
$it = new RecursiveDirectoryIterator($root);
foreach(new RecursiveIteratorIterator($it) as $file){
if($file->getBasename() === $toSearch){
printf("Found it! It's %s", $file->getRealPath());
// stop at the first match
break;
}
}
Keep in mind that depending on the number of files you have, this can be slow as hell
For a start this line is at fault
if ($title = '') {
See http://www.php.net/manual/en/reserved.variables.files.php

PHP/regex : Script to create filenames with dashes instead of spaces

I want to amend a PHP script I'm using in wordPress (Auto Featured Image plugin).
The problem is that this script creates filenames for thumbnails based on the URLs of the image.
That sounds great until you get a filename with spaces and the thumbnail is something like this%20Thumbnail.jpg and when the browser goes to http://www.whatever.com/this%20Thumbnail.jpg it converts the %20 to a space and there is no filename on the server by that name (with spaces).
To fix this, I think I need to change the following line in such a way that $imageURL is filtered to convert %20 to spaces. Sound right?
Here is the code. Perhaps you can tell me if I'm barking up the wrong tree.
Thank you!
<?php
static function create_post_attachment_from_url($imageUrl = null)
{
if(is_null($imageUrl)) return null;
// get file name
$filename = substr($imageUrl, (strrpos($imageUrl, '/'))+1);
if (!(($uploads = wp_upload_dir(current_time('mysql')) ) && false === $uploads['error'])) {
return null;
}
// Generate unique file name
$filename = wp_unique_filename( $uploads['path'], $filename );
?>
Edited to a more appropriate and complete answer:
static function create_post_attachment_from_url($imageUrl = null)
{
if(is_null($imageUrl)) return null;
// get the original filename from the URL
$filename = substr($imageUrl, (strrpos($imageUrl, '/'))+1);
// this bit is not relevant to the question, but we'll leave it in
if (!(($uploads = wp_upload_dir(current_time('mysql')) ) && false === $uploads['error'])) {
return null;
}
// Sanitize the filename we extracted from the URL
// Replace any %-escaped character with a dash
$filename = preg_replace('/%[a-fA-F0-9]{2}/', '-', $filename);
// Let Wordpress further modify the filename if it may clash with
// an existing one in the same directory
$filename = wp_unique_filename( $uploads['path'], $filename );
// ...
}
You better to replace the spaces in image name with underscores or hypens using regexp.
$string = "Google%20%20%20Search%20Amit%20Singhal"
preg_replace('/%20+/g', ' ', $string);
This regex will replace multiple spaces (%20) with a single space(' ').

PHP readir results - trying to sort by date created and also get rid of "." and ".."

I have a double question. Part one: I've pulled a nice list of pdf files from a directory and have appended a file called download.php to the "href" link so the pdf files don't try to open as a web page (they do save/save as instead). Trouble is I need to order the pdf files/links by date created. I've tried lots of variations but nothing seems to work! Script below. I'd also like to get rid of the "." and ".." directory dots! Any ideas on how to achieve all of that. Individually, these problems have been solved before, but not with my appended download.php scenario :)
<?php
$dir="../uploads2"; // Directory where files are stored
if ($dir_list = opendir($dir))
{
while(($filename = readdir($dir_list)) !== false)
{
?>
<p><a href="http://www.duncton.org/download.php?file=login/uploads2/<?php echo $filename; ?>"><?php echo $filename;
?></a></p>
<?php
}
closedir($dir_list);
}
?>
While you can filter them out*, the . and .. handles always come first. So you could just cut them away. In particular if you use the simpler scandir() method:
foreach (array_slice(scandir($dir), 2) as $filename) {
One could also use glob("dir/*") which skips dotfiles implicitly. As it returns the full path sorting by ctime then becomes easier as well:
$files = glob("dir/*");
// make filename->ctime mapping
$files = array_combine($files, array_map("filectime", $files));
// sorts filename list
arsort($files);
$files = array_keys($files);

Best way to get files from a dir filtered by certain extension in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP list of specific files in a directory
use php scandir($dir) and get only images!
So right now I have a directory and I am getting a list of files
$dir_f = "whatever/random/";
$files = scandir($dir_f);
That, however, retrieves every file in a directory. How would I retrive only files with a certain extension such as .ini in most efficient way.
PHP has a great function to help you capture only the files you need. Its called glob()
glob - Find pathnames matching a pattern
Returns an array containing the matched files/directories, an empty array if no file matched or FALSE on error.
Here is an example usage -
$files = glob("/path/to/folder/*.txt");
This will populate the $files variable with a list of all files matching the *.txt pattern in the given path.
Reference -
glob()
If you want more than one extension searched, then preg_grep() is an alternative for filtering:
$files = preg_grep('~\.(jpeg|jpg|png)$~', scandir($dir_f));
Though glob has a similar extra syntax. This mostly makes sense if you have further conditions, add the ~i flag for case-insensitive, or can filter combined lists.
PHP's glob() function let's you specify a pattern to search for.
You can try using GlobIterator
$iterator = new \GlobIterator(__DIR__ . '/*.txt', FilesystemIterator::KEY_AS_FILENAME);
$array = iterator_to_array($iterator);
var_dump($array);
glob($pattern, $flags)
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
try this
//path to directory to scan
$directory = "../file/";
//get all image files with a .txt extension.
$file= glob($directory . "*.txt ");
//print each file name
foreach($file as $filew)
{
echo $filew;
$files[] = $filew; // to create the array
}
haven't tested the regex but something like this:
if ($handle = opendir('/file/path')) {
while (false !== ($entry = readdir($handle))) {
if (preg_match('/\.txt$/', $entry)) {
echo "$entry\n";
}
}
closedir($handle);
}

Categories