Delete files which has the same prefix - php

$prefix = 'something_prefix';
unlink($prefix.'.*');
the code above is not working, but I see some code like this below works just fine
unlink('*.jpg');
why? I am wonder is this going to work?
unlink('*.*');
how to delete the files which they begin with the same string? like this
same123.jpg
sametoo.png
samexxx.gif
they all begins with the string "same" but ends with different extension, how to do this?
I alread have a cheap way to do this, but I wonder if there is any better solution?

Try this code:
$mask = 'your_prefix_*.*';
array_map('unlink', glob($mask));
p.s. glob() requires PHP 4.3.0+

You can use glob for this. Something like this(didn't test it):
foreach (glob("something_prefix*.*") as $filename) {
unlink($filename);
}

Related

What is wrong with this regex PHP code?

I have a folder that stores some thousands of pictures files.
I want to change the name of each file that matches the condition.
The idea is if the file name has _10 change to _ten, if has _5 change to _five.
So, xxdf23_10hy.jpg should be xxdf23_tenhy.jpg, 16_5_gt5.jpg should change to 16_five_gt5.jpg. But if file mane is gdjd_7.jpg, do nothing.
The code is working good, but it is matching the string ".." that should not be matched.
This is the part of the code:
$photoPath="../pic/";
$dir = new DirectoryIterator($photoPath);
foreach ($dir as $fileinfo) {
$filename = $fileinfo->getFilename();
if(preg_match($filename, "/_10/")){
//change te name to "_ten"
}
elseif(preg_match($filename, "/_5/")){
//change te name to "_five"
}
}
Something is not good with the way I am using the preg_match function.
But if I try it inside regex tester it works good.
What am I missing?
You've got your subject and pattern switched in the preg_match() commands. Try this:
if (preg_match("/_10/", $filename)) {
// more code
}
http://php.net/manual/en/function.preg-match.php
No need for the overhead of regex here at all. Perhaps simple glob() and str_replace() would meet your needs.
$photoPath="../pic/";
$replacements = array(
'_5' => '_five',
'_10' => '_ten'
);
foreach ($replacements as $pattern => $replace) {
$files = glob($photoPath . '*' . $pattern . '*');
foreach($files as $file) {
$old_name = $file;
$new_name = str_replace($pattern, $replace, $old_name);
rename($old_name, $new_name);
}
}
Here we don't even use regex or PHP string searching functionality to find the files we want to change. We use glob() which is basically a direct call to underlying libc glob() function and should perform significantly better and with less memory usage than the DirectoryIterator with post-filter functionality you are currently using. DirectoryIterator is probably overkill here anyway unless you are doing more complex file operations. glob() would filter your file names for you, meaning you are not doing useless regex searches against every file contained in DirectoryIterator object like you are currently doing.
The actual filepath name change is executed using basic str_replace(). You don't currently show how you are doing this, but I would imagine you would implement something similar or possibly just use preg_replace() rather than preg_match() if you desire to stick with regex approach.

Retrieve part of a link in smarty

I have the following link:
http://anydomainname.com/user/username/about
I know that $smarty.server.REQUEST_URI will return user/username/about.
But I can't find a way to return the latest part of my link which is about.
How can I return it? I prefer a solution that does not require me to alter or add new functions in .php files.
Here's an alternative to Marcin's answer using PHP's basename() function instead of substr/strrpos:
{$smarty.server.REQUEST_URI|basename}
You can use:
{$smarty.server.REQUEST_URI|substr:($smarty.server.REQUEST_URI|strrpos:'/'+1)}
It finds the last / in this string and return everything after it.
It is working in Smarty 3.1.19

PHP Parse INI File gives me error about equal sign

I'm trying to parse out an INI file that has a URL as one of the variables to parse. Problem is, the URL contains a '=' in it, and parse_ini_file spits out an error. I tried to escape the character, but to no avail. Does this happen to anybody else? And if so, has anybody fixed it?
Have you enclosed the value in quotes? It shouldn't be a problem to have = in the value as long as you have quotes around your value. Example:
key1="http://www.google.com?q=test";
much better would be use INI_SCANNER_RAW as 3rd parameter of parse_ini_file
parse_ini_file($file, true, INI_SCANNER_RAW);
I had the same problem and it drove me insane! The problem ended up being something silly ... I had created the .ini file in Windows, using a file that I renamed to .ini. Apparently there was some markup left which was seen by PHP, but not in my Notepad++.
I deleted the .ini and created one on my Linux host. This resolved the problem. If you're using WAMP or XAMPP on Windows, try to create a new file with just notepad, which disregards any markup.
I know this is an old topic, but I ended up here looking for the same problem, so it might help someone else.
Here is a quick solution to fix parse_ini_* problems with equality sign. You can use also regex, exploding arrays, etc.
function parseIniFile($file) {
if (!is_file($file)) return null;
$iniFileContent = file_get_contents($file);
return parseIniString($iniFileContent);
}
/* solves the equalitiy sign problem */
function parseIniString($iniFileContent==''){
$iniArray = array();
$iniFileContentArray = explode("\n", $iniFileContent);
foreach ($iniFileContentArray as $iniFileContentArrayRow){
$iniArrayKey = substr($iniFileContentArrayRow, 0, strpos($iniFileContentArrayRow, '='));
$iniArrayValue = substr($iniFileContentArrayRow, (strpos($iniFileContentArrayRow, '=')+1));
$iniArray[$iniArrayKey] = $iniArrayValue;
}
return $iniArray;
}

How to extract substrings with PHP

PHP beginner's question.
I need to keep image paths as following in the database for the admin backend.
../../../../assets/images/subfolder/myimage.jpg
However I need image paths as follows for the front-end.
assets/images/subfolder/myimage.jpg
What is the best way to change this by PHP?
I thought about substr(), but I am wondering if there is better ways.
Thanks in advance.
you should save your image path in an application variable and can access from both admin and frontend
If ../../../../ is fixed, then substr will work. If not, try something like this:
newpath=substr(strpos(path, "assets"));
It might seem like an odd choice at first but you could use ltrim. In the following example, all ../'s will be removed from the beginning of $path.
The dots in the second argument have to be escaped because PHP would treat them as a range otherwise.
$path = ltrim('../../../../assets/images/subfolder/myimage.jpg', '\\.\\./');
$path will then be:
assets/images/subfolder/myimage.jpg
I suggest this
$path = "../../../../assets/images/subfolder/myimage.jpg";
$root = "../../../../";
$root_len = strlen($root);
if(substr($path, 0, $root_len) == $root){
echo substr($path, $root_len);
} else {
//not comparable
}
In this way you have a sort of control on which directory to consider as root for your images

Preg_match help : selecting files in a folder

I have the following code that selects all the different template files out of a folder... The file names I have are:
template_default.php
template_default_load.php
template_sub.php
template_sub_load.php
I only want to select the ones without the _load in the file name so I used this code:
preg_match('/^template_(.*)[^[_load]]{0}\.php$/i', $layout_file, $layout_name)
The code works fine except it cuts the last character off the result... Instead of returning default or sub when I echo $layout_name[1], it shows defaul and su...
Any ideas what is wrong with my code?
This part is totally up the creek:
[^[_load]]{0}
This is the regex you want:
/^template_(.*)(?<!_load)\.php$/i
You'll have to use negative assertions. (read below why not)
preg_match('/^template_(.*?)(?!_load)\.php$/i', $layout_file, $layout_name)
Edit: come to think of it, that regexp won't actually work because "_load" will be consumed by the .*? part. My advice: don't use preg_match() to capture the name, use it to skip those that end with _load, e.g.
foreach (glob('template_*') as $filepath)
{
if (preg_match('#_load\\.php$', $filepath))
{
// The file ends with _load
}
$filename = basename($filepath);
$layout_name = substr($filename, strlen('template_'));
}

Categories