Php file_exist with regex - php

I am trying to use regex pattern to search for files.
Directory path is:
$css_dir = MY_PLUGIN_DIR.'/source/css/';
Css filename starts with:
$css_prefix = 'hap_css_';
and ends with:
'.css'
With some amount of unknown characters in between.
I dont know how to construct regex pattern with variable and how to construct file exist with regex.
Thank you!

You can use glob():
$files = glob($css_dir . $css_prefix . '*.css');
However, you have to roll your own DirectoryIterator based solution for more complex filtering:
$dir = new DirectoryIterator($css_dir);
$pattern = '/^' . preg_quote($css_prefix) . '.+\\.css$' . '/';
foreach ($dir as $fileInfo) {
if (preg_match($pattern, $fileInfo->getBaseName())) {
// match!
}
}
(One could also integrate a RegexIterator):
The use of scandir() is possible as well:
$pattern = '/^' . preq_quote($css_prefix) . '.+\\.css$' . '/';
$files = array_filter(scandir($css_dir), function ($filename) {
return preg_match($pattern, $filename);
});

Related

How to display all files in directory using PHP 5.6

I have problem with files, for example .342342.jpg or .3423423.ico. The script below dosen't see this files. My script:
<?php
$filepath = recursiveScan('/public_html/');
function recursiveScan($dir) {
$tree = glob(rtrim($dir, '/') . '/*');
if (is_array($tree)) {
foreach($tree as $file) {
if (is_dir($file)) {
//echo $file . '<br/>';
//recursiveScan($file);
} elseif (is_file($file)) {
echo $file . '<br/>';
if (preg_match("[.a-zA-Z0-9]", $file )) {
echo $file . '<br/>';
//unlink($file);
}
}
}
}
}
?>
Use this \.[[:alnum:]]*as your regular expression to match a single dot and then any number of letters and digits afterwards, because as you're using it now it only matches a single character of any kind. Use regex101.com for future regular expression testing. It shows a detailed breakdown of what you're filtering for and has a great cheatsheet for all tokens you can use
AFAIK, glob doesn't return filenames that begin with a dot, so, .342342.jpg is not returned.
Your regex if (preg_match("[.a-zA-Z0-9]", $file )) { matches filenamess that contain .a-zA-Z0-9 (ie. xxx.a-zA-Z0-9yyy) I guess you want filenames that contain dot or alphanum, so your regex becomes:
if (preg_match("/^[.a-zA-Z0-9]+$/", $file )) {

Glob is not working when directory name with special characters like square brackets "[ ]"

I have issue while using glob function when path directory with square brackets.
// Example 1 - working
$path = 'temp'. DIRECTORY_SEPARATOR .'dir - name';
$files = glob($path . DIRECTORY_SEPARATOR . '*.txt');
// List all files
echo '<pre>';
print_r($files);
echo '</pre>';
Above code is working but when directory name with square brackets like dir[name] or dir - [name] then its not working.
// Example 2 - not working
$path = 'temp'. DIRECTORY_SEPARATOR .'dir - [name]';
$files = glob($path . DIRECTORY_SEPARATOR . '*.txt');
// result got empty if file on that directory
echo '<pre>';
print_r($files);
echo '</pre>';
Thanks for all of you.
I got exact solution for my query. below code is a working for me
$path = 'temp'. DIRECTORY_SEPARATOR .'dir - [name]';
$path = str_replace('[', '\[', $path);
$path = str_replace(']', '\]', $path);
$path = str_replace('\[', '[[]', $path);
$path = str_replace('\]', '[]]', $path);
$files = glob($path . DIRECTORY_SEPARATOR . '*.txt');
// List files
echo '<pre>';
print_r($files);
echo '</pre>';
This is what I use:
$path = str_replace(['[',']',"\f[","\f]"], ["\f[","\f]",'[[]','[]]'], $path);
All in one line.
[foo] has a special meaning, it represents a character class (regular expression syntax).
So to have [ and ] mean square brackets literally, you have to escape them – by preceding them with a backslash.
Try
$path = 'temp'. DIRECTORY_SEPARATOR .'dir - [name]';
$from = array('[',']');
$to = array('\[','\]');
$files =glob(str_replace($from,$to,$path . "\\*.txt"));
echo '<pre>';
print_r($files);
echo '</pre>';
Late to the party I know, but based on previous answers, and after testing on both Linux/Mac and Windows, I came up with this utility function:
function glob_escape($path){
return preg_match('/\[.+]/', $path) ? str_replace(['[',']', '\[', '\]'], ['\[','\]', '[[]', '[]]'], $path) : $path;
}
For practical reasons, the function only attempts to escape characters when there are opening and closing [brackets] in the $path, with minimum one character in between. Single-brackets some[folder and brackets without a char between some[]folder don't need to be escaped.
Usage example:
$path = 'some/dir[brackets]here/more[brackets]blah';
glob(glob_escape($path) . '/*', GLOB_NOSORT|GLOB_ONLYDIR);
Tested on Linux and Windows.

Find string in multiple files

I need to check if $string exists in one of the files in a folder. Below is what I have, but it's obviously not working. What am I missing?
foreach (glob($path . 'foo/bar/*.*') as $file) {
if (strpos(file_get_contents($file), $string) !== false) {
//** found
} else {
//** not found
}
}
Are you sure all your files include an extension? You could try
glob($path . 'foo/bar/*')
and see if that works.
Also, if you're using Windows you should use a backslash (\) instead of a forward slash (/). You could use the DIRECTORY_SEPARATOR constant to let PHP automate it for you.
glob($path . 'foo' . DIRECTORY_SEPARATOR . 'bar' . DIRECTORY_SEPARATOR . '*.*')
Are you also sure that $path ends with a slash?

How to remove part of a url?

Trying to turn this:
href="/wp-content/themes/tray/img/celebrity_photos/photo.jpg"
into:
href="/img/celebrity_photos/photo.jpg"
So I'm simply trying to remove /wp-content/themes/tray/ from the url.
Here's the plug in's PHP code that builds a variable for each anchor path:
$this->imageURL = '/' . $this->path . '/' . $this->filename;
So I'd like to say:
$this->imageURL = '/' . $this->path -/wp-content/themes/tray/ . '/' . $this->filename;
PHP substr()? strpos()?
Given that:
$this->imageURL = '/' . $this->path . '/' . $this->filename;
$remove = "/wp-content/themes/tray";
This is how to remove a known prefix, if it exists:
if (strpos($this->imageURL, $remove) === 0) {
$this->imageURL = substr($this->imageURL, strlen($remove));
}
If you are certain that it always exists then you can also lose the if condition.
This is one option:
$h="/wp-content/themes/tray/img/celebrity_photos/photo-on-4-6-12-at-3-23-pm.jpg";
$prefix="/wp-content/themes/tray/";
print str_replace($prefix, "/", $h, 1);
It suffers from one major flaw, which is that it doesn't anchor itself to the left-hand-side of $h. To do this, you'd either need to use a regular expression (which is heavier on processing) or wrap this in something that detects the position of your prefix before running the str_replace().
$h="/wp-content/themes/tray/img/celebrity_photos/photo-on-4-6-12-at-3-23-pm.jpg";
$prefix="/wp-content/themes/tray/";
if (strpos(" ".$h, $prefix) == 1)
$result = str_replace($prefix, "/", $h, 1);
else
$result = $h;
print $result;
Note this important element: the prefix ends in a slash. You don't want to match other themes like "trayn" or "traypse". Beware writing things for just your specific use case. Always try to figure out how code might break, and program around problematic hypothetical use cases.
Try this :
$href = str_replace("/wp-content/themes/tray","",$href);
Or in your specific case, something like this :
$this->imageURL = '/' . str_replace("/wp-content/themes/tray/","",$this->path) . '/' . $this->filename;

Creating a directory in PHP based on a bunch of variables

I've been trying to create a directory following a specific structure, yet nothing appears to be happening. I've approached this by defining multiple variables as follows:
$rid = '/appicons/';
$sid = '$artistid';
$ssid = '$appid';
$s = '/';
and the function I've been using runs thusly:
$directory = $appid;
if (!is_dir ($directory))
{
mkdir($directory);
}
That works. However, I want to have the following structure in created directories: /appicons/$artistid/$appid/
yet nothing really seems to work. I understand that if I were to add more variables to $directory then I'd have to use quotes around them and concatenate them (which gets confusing).
Does anyone have any solutions?
$directory = "/appicons/$artistid/$appid/";
if (!is_dir ($directory))
{
//file mode
$mode = 0777;
//the third parameter set to true allows the creation of
//nested directories specified in the pathname.
mkdir($directory, $mode, true);
}
This should do what you want:
$rid = '/appicons/';
$sid = $artistid;
$ssid = $appid;
$s = '/';
$directory = $rid . $artistid . '/' . $appid . $s;
if (!is_dir ($directory)) {
mkdir($directory);
}
The reason your current code doesn't work is due to the fact you're trying to use a variable inside a string literal. A string literal in PHP is a string enclosed in single quotes ('). Every character in this string is treated as just a character, so any variables will just be parsed as text. Unquoting the variables so your declarations look like the following fixes your issue:
$rid = '/appicons/';
$sid = $artistid;
$ssid = $appid;
$s = '/';
This next line concatenates (joins) your variables together into a path:
$directory = $rid . $artistid . '/' . $appid . $s;
Concatenation works like this
$directory = $rid.$artistid."/".$appid."/"
When you're assigning one variable to another, you don't need the quotes around it, so the following should be what you're looking for.
$rid = 'appicons';
$sid = $artistid;
$ssid = $appid;
and then...
$dir = '/' . $rid . '/' . $sid . '/' . $ssid . '/';
if (!is_dir($dir)) {
mkdir($dir);
}

Categories