I really need some help with this... i just cant make it work.
For now i have this piece of code and it's working fine.
What it does is... retuns all files within a directory according to date in their name.
<?php
header('Access-Control-Allow-Origin: *');
$imagesDir = '';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$filteredImages = [];
foreach($images as $image) {
$current_date = date("Ymd");
$file_date = substr($image, 0, 8);
if (strcmp($current_date, $file_date)>=0)
$filteredImages[] = $image;
}
echo json_encode($filteredImages, JSON_UNESCAPED_UNICODE);
?>
But now i need to filter those files (probably before this code is even executed). acording to the string in their name.
files are named in the following manner:
yyyymmdd_xxxxxxx-xxxxxx~yyyymmdd.123456789.jpg
yyyymmdd_xxxxxxx-xxxxxx~yyyymmdd.9.jpg
yyyymmdd_xxxxxxx-xxxxxx~yyyymmdd.458.jpg
i need to filter out only ones that have certain number within that string of numbers at the end (between "." and ".jpg") eg. number 9
$number = 9
i was trying with this piece of code to seperate only that last part of name:
<?php
function getBetween($jpgname,$start,$end){
$r = explode($start, $jpgname);
if (isset($r[1])){
$r = explode($end, $r[1]);
return $r[0];
}
return '';
}
$jpgname = "yyyymmdd_xxxxxxx-xxxxxx~yyyymmdd.12789.jpg";
$start = ".";
$end = ".jpg";
$output = getBetween($jpgname,$start,$end);
echo $output;
?>
and i guess i would need STRIPOS within all of this... but im lost now... :(
You can probably use preg_grep.
It's regex for arrays.
This is untested but I think it should work.
header('Access-Control-Allow-Origin: *');
$imagesDir = '';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$find = 9;
$filtered = preg_grep("/.*?\.\d*" . $find . "\d*\./", $images);
The regex will look for anything to a dot then any number or no number, the $find then any or no number again and a dot again.
Is this what you need ? It will give you 123456789
$string = "yyyymmdd_xxxxxxx-xxxxxx~yyyymmdd.123456789.jpg";
$explode = explode(".", $string);
echo ($explode[1]);
Edit -
As per your requirement Andreas's solution seems to be working.
This is what I tried , I changed the find variable and checked.
$images = array("yyyymmdd_xxxxxxx-xxxxxx~yyyymmdd.12789.jpg");
$find = 32;
$filtered = preg_grep("/.*?." . $find . "./", $images);
print_r($filtered);
Related
Goodevening to everyone, how can i add a number to a file name in php.
Let me explain; I want to save a file using a dropzone but i want to rename the file if it exist in the folder.
I've written down this code but the regex doesn't work and also if it's possible to insert the number before the extension of the file like google chrome does.
if(file_exists($target_file)){
if(preg_match_all($target_file, "'('[0-9]{1,}')'")==false){
$target_file= $target_path."(1)".$name;
}else{
$pos=preg_match_all($target_file, "'('[0-9]{1,}')'");
$pos=$pos++;
$pos1=strpos($pos, $target_file, ")");
$pos1=$pos1-$pos;
$num=substr($target_file, $pos, $pos1);
$num = (int)$num;
$num =$num++;
$sostituisci="(".$num.")";
$target_file=preg_replace("'('[0-9]{1,}')'", $sostituisci, $target_file);
}
}
$name is the name of the file i want to save with the extension
the first $target_file of the code contain the full path + the name of the file
$target_file is a sting like /dropzone/upload/filename.txt and $name is a string like filename.txt. If the $targetfile exist i would to rename the $name like filename(1).txt or filename(2).txt and so on
also other solutions are accepted like a js library.
I assume you are referring to this set of code here.
if(preg_match_all($target_file, "'('[0-9]{1,}')'")==false){
$target_file= $target_path."(1)".$name;
}
insert the number before the extension of the file
EDIT: Use explode() and re-format the ext.
EXAMPLE:
$target_path = "/assets/imgages/";
$name = 'img.jpg';
$name = explode('.', $name);
$format = $name[0].'(1).'.$name[1];
$path = $target_path.$format;
Will produce the following string:
/assets/img/notes(1).txt
Accept multiple dots in string.
$filename = 'company.jobtitle.field.text';
function formatDuplicateExtension($filename){
$stmt = NULL;
$format = explode('.', $filename);
$i = 0;
foreach($format as $key => $value){
if($value === end($format)){
$stmt .= '(1).'.$format[$i];
}elseif($key === count($format)-2){
$stmt .= $format[$i];
}else{
$stmt .= $format[$i].'.';
}
$i++;
}
return $stmt;
}
echo formatDuplicateExtension($filename);
$filename = 'company.jobtitle.field.text';
OUTPUTS: //-->/assets/imgages/company.jobtitle.field(1).text
$name = 'trees.vac2012.img.jpg';
OUTPUTS: //--> /assets/imgages/trees.vac2012.img(1).jpg
I've found a solution idk if it's the best one because regex searches and substitutions are involved a lot of times and it seems to be they're resources consuming functions.
//this function insert the $number in the name of the file before .extension
function InsertBeforeExtension($filename,$number){
$stmt = NULL;
$format = explode('.', $filename);
$i = 0;
foreach($format as $key => $value){
if($value === end($format)){
$stmt .= '('.$number.').'.$format[$i];
}elseif($key === count($format)-2){
$stmt .= $format[$i];
}else{
$stmt .= $format[$i].'.';
}
$i++;
}
return $stmt;
}
//this function check if there's a string like (number).ext in the name
//if yes increment the (number) in the string that become (number++).ext
//if no insert (1) before .ext
function insertnumber($string){
$matches=array();
$re = '/[(][0-9]+[)]\.[a-zA-Z]+/m';
preg_match_all($re, $string, $matches, PREG_SET_ORDER, 0);
if($matches[0][0]){
//if (number).ext is present
$re = '/[(][0-9]+[)]/m';
$str = $matches[0][0];
//select the (number) only
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
//remove parethesis
$str=substr($matches[0][0],1,-1);
//cast sting to an int for add a number
$int = (int)$str;
$int++;
//replace the last (number) match in the name of the file with (number++)
$re = '/(.*)[(][0-9]+[)]/m';
$subst = '${1}('.$int.')';
$result = preg_replace($re, $subst, $string);
}else{
//if (number).ext is not present insert (1) before .ext
$result=InsertBeforeExtension($string,1);
}
return $result;
};
$target_file = $target_path.$name;
//If the file exist repeat to find the number of file that doesn't exist
if( file_exists( $target_file )) {
while(file_exists( $target_file )){
$name=insertnumber($name);
$target_file = $target_path.$name;
}
}
The only problem is that if you have uploaded a file named like file(3).txt and you upload another file with the same name this function rename it in file(4).txt and not in file(3)(1).txt but for my scope this is not important
I've commented the code trying to be the most clear possible this solution seems to work well but i've not calculate the performance.
I'm facing some problem with php regex but after many researches (conditional regex, subpattern regex), I still can't solve it.
I have a folder that contains many images and based on variable value I have to go to that folder and select all images that match the value.
e.g: In my folder I have 3 images:
p102.jpg ; p1020.jpg ; p102_1.jpg;
I only want the regex to select :
p102.jpg ; p102_1.jpg
but with the regex below It selects all 3 images.
$image_to_find = 102;
$path = "[^\d]*.*/"
$test = "/^[a-zA-Z]?$image_to_find".$path;
foreach(glob($file_directory) as $file){
if(preg_match($test, $file)){
match[]= $file;
}
}
I also try:
$path = "(?:\_[0-9]?).*/"; (it selects only p102_1.jpg)
Can you help me to figure it out. thanks
(sorry for the english)
You can avoid the foreach loop if you use the glob pattern:
$num = 102;
$result = glob($path . '[a-zA-Z]' . $num . '[._]*');
Note: if you need to allow several different formats, you can use array_merge and several glob patterns: array_merge(glob(...), glob(...));
If you want the first letter optional:
$result = array_merge(
glob($path . $num . '[._]*jpg'),
glob($path . '[a-zA-Z]' . $num . '[._]*jpg')
);
or better, use the brace option:
$result = glob($path . '{[a-zA-Z],}' . $num . '[._]*jpg', GLOB_BRACE);
That stays a better alternative than the combo "foreach/preg_match" (or preg_grep) if filenames are not too complicated.
With preg_grep:
$pattern = '~(?:^|/)[a-z]?' . $num . '(?:_\d+)?\.jpg$~i';
$result = preg_grep($pattern, glob($path . '*' . $num . '*.jpg'));
Try this:
/p102[_\.]\d*\.?jpg/g
https://regex101.com/r/hM4oE0/1
Where p102 should be your 'image_to_find' var.
Not tested, should work.
$find = 102;
$pattern = "/p". $find ."(?:_\d+)?\.jpg/";
$list = array();
foreach (glob($file_directory) as $file)
{
if (preg_match($pattern, $file))
{
$list[] = $file;
}
}
regex: http://regexr.com/3bp29
Tested and working:
<?php
$image_to_find = 102;
$pattern = '[a-zA-Z]' . $image_to_find . '[._]*';
$path = '/your_folder/your_subfolder/';
$file_directory = glob($path . $pattern );
echo '<pre>';
var_dump($file_directory);
echo '</pre>';
exit();
I hope this helps!
I'm getting a ftp_rawlist of files from FTP in PHP.
I take the rawlist and run this code:
foreach ($ftp_rawlist AS $ff) {
$ff = preg_split("/[\s]+/", $ff, 9);
$perms = $ff[0];
$user = $ff[2];
$group = $ff[3];
$size = $ff[4];
$month = $ff[5];
$day = $ff[6];
$file = $ff[8];
}
This works fine, but if a $ff[8] has a space at the beginning of the file name, my code doesn't parse it to $file.
E.g. " file.pdf" is parsed as "file.pdf"
I'm not sure how to modify my preg_split to capture spaces.
Try this: Remove the + symbol from the regexp by doing:
$ff = preg_split("/[\s]/", $ff, 9);
Cheers.
i am uploading the image into the server , need to place the _ in place of gap in the image. Like if the name of image is Stack Flow.jpg, i need to send it as Stack_Flow.jpg in the directory as well in the email. HOw could be possible with the following code. i have tried but no success.. I am sending the 4 files in one form, code as ---
$filea = $_FILES['FILE1']['name'];
$fileb = $_FILES['FILE2']['name'];
$filec = $_FILES['FILE3']['name'];
$filed = $_FILES['FILE4']['name'];
$order_image_a='order_'.$orderId.'_'.$filea;
if(!empty($filea)) move_uploaded_file($_FILES['FILE1']['tmp_name'], "../files/$order_image_a");
$order_image_b='order_'.$orderId.'_'.$fileb;
if(!empty($fileb)) move_uploaded_file($_FILES['FILE2']['tmp_name'], "../files/$order_image_b");
$order_image_c='order_'.$orderId.'_'.$filec;
if(!empty($filec)) move_uploaded_file($_FILES['FILE3']['tmp_name'], "../files/$order_image_c");
$order_image_d='order_'.$orderId.'_'.$filed;
if(!empty($filed)) move_uploaded_file($_FILES['FILE4']['tmp_name'], "../files/$order_image_d");
i am using below function, how could i apply it for all four files--
<script>
function convertSpecialChars($str) {
$str = str_replace( " ", "_", $str );
return $str;
}
</script>
here is a quick example in php:
<?php
$name = "Stack Flow.jpg";
echo preg_replace('/[\s\-]+/', '_', $name );
?>
returns Stack_Flow.jpg
http://codepad.org/MQoEZ2wv
This is not a script but PHP..
<?
function convertSpecialChars($str) {
$str = str_replace( " ", "_", $str );
return $str;
?>
//do the same for all other images..
$filea = str_replace(' ', '_', $filea;
$order_image_a='order_'.$orderId.'_'.$filea;
if(!empty($filea)) move_uploaded_file($_FILES['FILE1']['tmp_name'], "../files/$order_image_a");
Using:
<?php
function convertSpecialChars($str) {
$str = str_replace( " ", "_", $str );
return $str;
}
?>
And then your code:
$filea = $_FILES['FILE1']['name'];
$fileb = $_FILES['FILE2']['name'];
$filec = $_FILES['FILE3']['name'];
$filed = $_FILES['FILE4']['name'];
$order_image_a='order_'.$orderId.'_'.convertSpecialChars($filea);
if(!empty($filea))
move_uploaded_file($_FILES['FILE1']['tmp_name'], "../files/$order_image_a");
$order_image_b='order_'.$orderId.'_'.convertSpecialChars($fileb);
if(!empty($fileb))
move_uploaded_file($_FILES['FILE2']['tmp_name'], "../files/$order_image_b");
$order_image_c='order_'.$orderId.'_'.convertSpecialChars($filec);
if(!empty($filec))
move_uploaded_file($_FILES['FILE3']['tmp_name'], "../files/$order_image_c");
$order_image_d='order_'.$orderId.'_'.convertSpecialChars($filed);
if(!empty($filed))
move_uploaded_file($_FILES['FILE4']['tmp_name'], "../files/$order_image_d");
Or if possible, you could do it in a loop (less duplicate code):
for ($i = 1; $i <= 4; $i++)
{
$file = $_FILES['FILE' . $i]['name'];
$order_image = 'order_' . $orderId . '_' . convertSpecialChars($file);
if(!empty($file))
move_uploaded_file($_FILES['FILE' . $i]['tmp_name'], "../files/$order_image");
}
In your code change $order_image_a='order_'.$orderId.'_'.$filea; and other similar lines to
$order_image_a='order_'.$orderId.'_'.convertSpecialChars($filea);
But will better if you will know how work your code.
I have asked in two earlier questions to place multiple markers from a XML file created from Lightroom, which had to be tranformed in degrees instead of Degrees,Minutes,Seconds.
This part i managed but then...
The answers in the previous question were very informative but it's my poor skill of programming (first project) that i just cannot manage to solve it.
The problem is i want to show multiple markers.
the complete code:
<?php
require('GoogleMapAPI.class.php');
$objDOM = new DOMDocument("1.0", 'utf-8');
$objDOM->preserveWhiteSpace = false;
$objDOM->load("googlepoints.xml"); //make sure path is correct
$photo = $objDOM->getElementsByTagName("photo");
foreach ($photo as $value) {
$album = $value->getElementsByTagName("album");
$albu = $album->item(0)->nodeValue;
$description = $value->getElementsByTagName("description");
$descriptio = $description->item(0)->nodeValue;
$title = $value->getElementsByTagName("title");
$titl = $title->item(0)->nodeValue;
$link = $value->getElementsByTagName("link");
$lin = $link->item(0)->nodeValue;
$guid = $value->getElementsByTagName("guid");
$gui = $guid->item(0)->nodeValue;
$gps = $value->getElementsByTagName("gps");
$gp = $gps->item(0)->nodeValue;
$Deglon = str_replace("'", "/", $gp);
$Deglon = str_replace("°", "/", $Deglon);
$Deglon = str_replace("", "/", $Deglon);
$str = $Deglon;
$arr1 = str_split($str, 11);
$date = $arr1[0]; // Delimiters may be slash, dot, or hyphen
list ($latdeg, $latmin, $latsec, $latrichting) = split ('[°/".-]', $date);
$Lat = $latdeg + (($latmin + ($latsec/60))/60);
$latdir = $latrichting.$Lat;
If (preg_match("/N /", $latdir)) {$Latcoorl = str_replace(" N ", "+",$latdir);}
else {$Latcoorl = str_replace ("S ", "-",$latdir);}
//$Latcoord=$Latcoorl.",";
$date1 = $arr1[1]; // Delimiters may be slash, dot, or hyphen
list ($londeg, $lonmin, $lonsec, $lonrichting) = split ('[°/".-]', $date1);
$Lon = $londeg + (($lonmin + ($lonsec/60))/60);
$londir = $lonrichting.$Lon;
If (preg_match("/W /", $londir)) {$Loncoorl = str_replace("W ", "+",$londir);}
else {$Loncoorl = str_replace ("E", "-",$londir);}
$Lonarr = array($Loncoorl);
foreach ($Lonarr as &$LonArray);
$Latarr = array($Latcoorl);
foreach ($Latarr as &$LatArray);
$titarr = array($titl);
foreach ($titarr as &$titArray);
$guarr = array($gui);
foreach ($guarr as &$guaArray);
$albuarr = array($albu);
foreach ($albuarr as &$albuArray);
print_r ($LonArray);
print_r ($LatArray);
print_r ($guaArray);
print_r ($albuArray);
$map = new GoogleMapAPI('map');
// setup database for geocode caching
// $map->setDSN('mysql://USER:PASS#localhost/GEOCODES');
// enter YOUR Google Map Key
$map->setAPIKey('ABQIAAAAiA4e9c1IW0MDrtoPQRaLgRQmsvD_kVovrOh_CkQEnehxpBb-yhQq1LkA4BJtjWw7lWmjfYU8twZvPA');
$map->addMarkerByCoords($LonArray,$LatArray,$albuArray,$guaArray);
}
?>
The problem is that the "$map->addMarkerByCoords($LonArray,$LatArray,$albuArray,$guaArray);" only shows the last value's from the 4 arrays.
And there fore there is only one marker created.
The output (print_r) of for example the $guaArray is IMG_3308IMG_3309IMG_3310IMG_3311IMG_3312 (5 name's of filename's from photographs).
The function addMarkersByCoords from the 'GoogleMapAPI.class.php' is like this:
function addMarkerByCoords($lon,$lat,$title = '',$html = '',$tooltip = '') {
$_marker['lon'] = $lon;
$_marker['lat'] = $lat;
$_marker['html'] = (is_array($html) || strlen($html) > 0) ? $html : $title;
$_marker['title'] = $title;
$_marker['tooltip'] = $tooltip;
$this->_markers[] = $_marker;
$this->adjustCenterCoords($_marker['lon'],$_marker['lat']);
// return index of marker
return count($this->_markers) - 1;
}
I hope that someone can help me ?
You must create the new instance of the google map above the foreach
like this
$map = new GoogleMapAPI('map');
// setup database for geocode caching
// $map->setDSN('mysql://USER:PASS#localhost/GEOCODES');
// enter YOUR Google Map Key
$map->setAPIKey('ABQIAAAAiA4e9c1IW0MDrtoPQRaLgRQmsvD_kVovrOh_CkQEnehxpBb-yhQq1LkA4BJtjWw7lWmjfYU8twZvPA');
foreach ()
{
}
now you are creating every loop a new map with the last coord
Your foreach loops aren't accomplishing annything useful:
$Lonarr = array($Loncoorl);
foreach ($Lonarr as &$LonArray);
$LonArray is just one element from the $Lonarr array. I think the foreach loop is adding each element of the array onto one big string ($LonArray).