I have a directory containing folders like
baseurl/2-435435435_323423/
baseurl/5_435435435_32423/
baseurl/3_543543543_2342342/
Now i want to rename all the folders from their original name to new name i.e. truncate last part separated by '_'. new names would be
baseurl/2-435435435/
baseurl/5_435435435/
baseurl/3_543543543/
$path_from = 'E:/documents/';
if(file_exists($path_from)){
$files = scandir($path_from);
foreach($files as $key1 => $file) {
$newName = ? // I need this
rename($path_from.$file,$path_from.$newName);
}
}
Or Let me know if there is anyway in windows to rename batch without any script.
As you mention for getting only $newName, Just use substr and strrpos.
strrpos - Find the numeric position of the last occurrence of a string
$str = 'baseurl/3_543543543_2342342/';
$pos = strrpos($str, "_");
if ($pos === false){
//do nothing
}else
$str = substr($str, 0, $pos)."/";
echo $newName = $str; //baseurl/3_543543543/
You can make use of strstr
$path_from = 'E:/documents/';
if(file_exists($path_from)){
$files = scandir($path_from);
foreach($files as $key1 => $file) {
$newName = strstr($file, '_', true);
rename($path_from.$file,$path_from.$newName);
}
}
e.g.
$str = 'baseurl/2-435435435_323423/';
$imagePreFix = strstr($str, '_', true);
echo $imagePreFix;
OUTPUT:
baseurl/2-435435435
$newName = substr($file, 0, strrpos($file, '_'));
Related
I want to compare $images, $uploads but the outputs have different names:
$images = '/fiscalapplications/uploads/Image_00314_20200122.pdf';
$uploads = 'Image_00314_20200122.pdf';
How do I do SUBSTR for the $images to = Image_00314_20200122.pdf
<?php
//pulling images from mysql colum1
require_once 'database_connection.php';
$result = mysqli_query($conn,"SELECT check_pic_path FROM checklog");
$images = []; // store a list of images from the database
while ($row = mysqli_fetch_array($result)) {
$images[] = $row['check_pic_path'] . "<br>";
}
//pulling pictures from specific path
$dir = "fiscalapplications/uploads";
$uploads = []; // store a list of files on disk
if(is_dir($dir)) {
while (($file = readdir($dh)) !== false) {
$uploads[] = $file . "<br>";
}
}
}
//attempting to compare $image to $upload
$compare = array_diff($images, $uploads);
print_r($compare);
Use basename() to remove the directory from a pathname:
$images[] = basename($row['check_pic_path']) . "<br>";
In MySQL it may be
SUBSTRINT_INDEX(tablename.imagefield, '/', -1)
$uploadsnew = substr($images , strrpos($images , '/') + 1);
strrpos gets the position of the last occurrence of the slash; substr returns everything after that position.
if there is no slash this doesn't work correctly since strrpos returns false. Here's a more robust version:
$pos = strrpos($url, '/');
$uploadsnew = $pos === false ? $url : substr($images , $pos + 1);
In PHP:
$images = $images ?: '';
$uploads = substr($images, ($pos = strrpos($images, '/')) ? $pos : 0);
In MySQL:
if( ifnull( locate( '/', check_pic_path ), 0 ) > 0, substring_index( check_pic_path, '/', -1 ), check_pic_path )
I need a PHP script to print customer names in a file. There's hundreds of names and addresses but I want to print only the names with a maximum of 15 letters.
<?php
$file = file_get_contents('data-cust.txt');
$keyword = 'name';
$str = substr($file, strpos($file, $keyword) + strlen($keyword), 15);
echo $str;
?>
I tried using the above but only printed one name. How do I make it print all names?
Thanks.
If the names are on their own line, something like this should work.
<?php
$file = file('data-cust.txt');
foreach($file as $line) {
$keyword = 'name';
$str = substr($line, strpos($line, $keyword) + strlen($keyword), 15);
echo $str;
}
You need to open the file and read it then extract the names.
$file = fopen("data-cust.txt", "r");
$keyword = 'name';
$str = array() ;
if ($file) {
while (($line = fgets($file )) !== false) {
$name = substr($line, strpos($line, $keyword) + strlen($line), 15);
echo $name ;
$str[] = $name ;
}
} else {
// error opening file
}
fclose($file );
print_r($str) ;
Suppose I have the following piece of code:
$myString = 'FilE.EXE';
strlower($myString);
I want to make the name minus its extension to lower case, but the code above will make the entire string into lower case. Is there a way I can just change the name without the extension? If so, what is the most dynamic way to accomplish this?
Desired output: 'file.EXE';
Using pathinfo
$myString = 'FilE.EXE';
$new_string = strtolower(pathinfo($myString, PATHINFO_FILENAME)) . '.' . pathinfo($myString, PATHINFO_EXTENSION);
echo $new_string;
You need to do something like this:
$string = "FilE.EXE";
list($name, $extension) = explode('.', $string);
$string = implode('.', array(strtolower($name), $extension));
Hope it helps.
do:
$myString = 'FilE.EXE';
$txt = strtolower( substr( $myString, 0, strrpos($myString, ".") ) )
.substr( $myString, strrpos($myString, "."), strlen($myString));
echo $txt; //gives file.EXE
You might want to use the pathinfo() function for that:
$myString = 'FilE.iNc.EXE';
$path_parts = pathinfo($myString);
$myNewString = implode('.', array(
strtolower($path_parts['filename']),
$path_parts['extension']
));
So it can ouput this:
file.inc.EXE
<?php
$myString = 'FilE.EXE';
$txt = strtolower( substr( $myString, 0, strrpos($myString, ".") ) );
$hell = substr( $myString, strrpos($myString, "."), strlen($myString));
$babe = $txt.$hell;
echo $babe;
I have a folder that contains files named standard_xx.jpg (xx being a number)
I would like to find the highest number so that I can get the filename ready to rename the next file being uploaded.
Eg. if the highest number is standard_12.jpg
$newfilename = standard_13.jpg
I have created a method to do it by just exploding the file name but it isn't very elegant
$files = glob($uploaddir.'test-xrays-del/standard_*.JPG');
$maxfile = $files[count($files)-1];
$explode = explode('_',$maxfile);
$filename = $explode[1];
$explode2 = explode('.',$filename);
$number = $explode2[0];
$newnumber = $number + 1;
$standard = 'test-xrays-del/standard_'.$newnumber.'.JPG';
echo $newfile;
Is there a more efficient or elegant way of doing this?
I'd do it like this myself:
<?php
$files = glob($uploaddir.'test-xrays-del/standard_*.JPG');
natsort($files);
preg_match('!standard_(\d+)!', end($files), $matches);
$newfile = 'standard_' . ($matches[1] + 1) . '.JPG';
echo $newfile;
You can make use of sscanfDocs:
$success = sscanf($maxfile, 'standard_%d.JPG', $number);
It will allow you to not only pick out the number (and only the number) but also whether or not this worked ($success).
Additionally you could also take a look into natsortDocs to actually sort the array you get back for the highest natural number.
A complete code-example making use of these:
$mask = 'standard_%s.JPG';
$prefix = 'test-xrays-del';
$glob = sprintf("%s%s/%s", $uploaddir, $prefix, sprintf($mask, '*'));
$files = glob($glob);
if (!$files) {
throw new RuntimeException('No files found or error with ' . $glob);
}
natsort($files);
$maxfile = end($files);
$success = sscanf($maxfile, sprintf($mask, '%d'), $number);
if (!$success) {
throw new RuntimeException('Unable to obtain number from: ', $maxfile);
}
$newnumber = $number + 1;
$newfile = sprintf("%s/%s", $prefix, sprintf($mask, $newnumber));
Try with:
$files = glob($uploaddir.'test-xrays-del/standard_*.JPG');
natsort($files);
$highest = array_pop($files);
Then get it's number with regex and increase value.
Something like this:
function getMaxFileID($path) {
$files = new DirectoryIterator($path);
$filtered = new RegexIterator($files, '/^.+\.jpg$/i');
$maxFileID = 0;
foreach ($filtered as $fileInfo) {
$thisFileID = (int)preg_replace('/.*?_/',$fileInfo->getFilename());
if($thisFileID > $maxFileID) { $maxFileID = $thisFileID;}
}
return $maxFileID;
}
If I have a string in the following format: location-cityName.xml how do I extract only the cityName, i.e. a word between - (dash) and . (period)?
Try this:
$pieces = explode('.', $filename);
$morePieces = explode('-', $pieces[0]);
$cityname = $morePieces[1];
Combine strpos() and substr().
$filename = "location-cityName.xml";
$dash = strpos($filename, '-') + 1;
$dot = strpos($filename, '.');
echo substr($filename, $dash, ($dot - $dash));
There are a few ways... this one is probably not as efficient as the strpos and substr combo mentioned above, but its fun:
$string = "location-cityName.xml";
list($location, $remainder) = explode("-", $string);
list($cityName, $extension) = explode(".", $remainder);
As i said... there are lots of string manipulation methods in php and you could do it many other ways.
Here's another way to grab the location as well, if you want:
$filename = "location-cityName.xml";
$cityName = preg_replace('/(.*)-(.*)\.xml/', '$2', $filename);
$location = preg_replace('/(.*)-(.*)\.xml/', '$1', $filename);
Here is a regular-expression–based approach:
<?php
$text = "location-cityName.xml";
if (preg_match("/^[^-]*-([^.]+)\.xml$/", $text, $matches)) {
echo "matched: {$matches[1]}\n";
}
?>
This will print out:
matched: cityName