Find File in directory Using php - php

I want Get Matched Files in php I have try Many More Time
for example ...
my directory files
1.254450_abcd.mp3
2.101215_apple.mp4
3.102545_efgf.php
i find only number like this 254450
$mypath = "/files/" ;
$find = "254450" ;
//i want get matched full name
echo "$filename" ;// get 254450_abcd.mp3
else
"file not found " ;

You can use scandir and preg_grep.
$mypath = "/files/" ;
$find = "254450" ;
$files = scandir($mypath);
$matches = preg_grep("/" . $find . "/", $files);
$matches is now an array with files matching $find
Here is a semi working example. I replaced scandir with your files in an array, just like scandir returns them.
https://3v4l.org/QullZ

Related

PHP: How to explode string

I have a variable that stores the location of a temp file:
$file = 'C:\xampp\htdocs\temp\filename.tmp';
How can I explode all this to get filename (without the path and extension)?
Thanks.
Is not the best code but if you confident that this path will be similar and just file name will be different you can use this code:
$str = 'C:\xampp\htdocs\temp\filename.tmp';
$arrayExplode = explode("\\", $str);
$file = $arrayExplode[count($arrayExplode)-1];
$filename = explode('.', $file);
$filename = $filename[0];
echo $filename;
Advice: Watch out on the path contain "n" like the first letter after the backslash. It could destroy your array.
You should use the basename function, it's meant specifically for that.

how to eliminate the first 2 entries from a path in php

i have a variable that shows me the path to a directory like below:
$dir = uploads/sha256/folder1/subfolder1/subsubfolder1
How can i "cut off" the first 2 directories from $dir so that it becomes:
$dir = folder1/subfolder1/subsubfolder1
sample code:
$dir = "uploads/sha256/folder1/subfolder1/subsubfolder1";
$pieces = explode("/", $dir);
echo $pieces[2]; // piece2
This gives me only folder1
And i need the complete path after the sha256
so what i actually try to achieve is something like this:
echo $pieces[>2];
You can capture () everything after the first two directories and replace with that:
$dir = preg_replace('#[^/]+/[^/]+/(.*)#', '$1', $dir);
Or you can explode it, slice all elements after the first two and implode it again:
$dir = implode('/', array_slice(explode('/', $dir), 2));

PHP GLOB more than one pattern at a time

code:
$matches = glob("$searchword*.txt", GLOB_BRACE) ;
that works, but i also have $secondword, so i read How to define multiple patterns in php glob()
so i tried
$matches = glob("{$searchword},{$secondword}*.txt", GLOB_BRACE) ;
$matches = glob("{$searchword,$secondword}*.txt", GLOB_BRACE) ;
$matches = glob("{$searchword*.txt},{$secondword*.txt}", GLOB_BRACE) ;
$matches = glob("$searchword*.txt", GLOB_BRACE) && ("$secondword*.txt", GLOB_BRACE);
$matches = (glob("$searchword*.txt", GLOB_BRACE) && ("$secondword*.txt", GLOB_BRACE));
results in invalid syntax
what im trying to do: list files via glob that are smilar to a $filename
is it possible to glob files that are similar to $filename?
references:
https://www.cowburn.info/2010/04/30/glob-patterns/
I've multiple txt files on my directory. Here I used glob with GLOB_BRACE and it perfectly showing the expected result to me.
$a = 'import_start_';
$b = '22_02_18_country_';
$m= glob("{{$a},{$b}}*.txt", GLOB_BRACE);
// OR //
// $m= glob({".$a.",".$b."}*.txt", GLOB_BRACE);
// OR //
print '<pre>';
print_r($m);
print '</pre>';
Output:
Array
(
[0] => import_start_date.txt
[1] => 22_02_18_country_list.txt
)

How to prevent words containing certain letters from being echoed out in PHP?

What happens here is that all the files in the directory are retrieved and then echoed out onto the page through PHP. The files contained in $blacklist are the ones that are not echoed out.
However, how could I change this so that if the file name (that is to be echoed out) contains the letters .txt all together in a row at the end of the word, it is then put into the blacklist so that it's not echoed out.
Does this make any sense?
<?php
$blacklist = array("one.jps", "two.txt", "four.html" , ".txt");
$files = array_diff(glob("*.*"), $blacklist);
foreach($files as $file)
echo "<div class='post'><a href='" . $_SERVER['PHP_SELF'] . "?file=" . $file . "'><p>" . $file . "</p></a></div>";
if(!empty($_GET["file"]) && !in_array($_GET["file"], $blacklist) && file_exists($_GET["file"]))
$thesource = htmlentities(file_get_contents($_GET["file"]));
?>
Assuming you want to keep $blacklist for further usage:
$blacklist = preg_grep("/\b.txt\b/", $files);
foreach (array_diff($files, $blacklist) as $whiteListedFile) {
// do your things
}
preg_grep is what you need here. Keep in mind that the example above will blacklists "file.txt" but not "file.txts" or "file.stxt" . Adjust the pattern for your needs. This is a good online regex tester for PHP.
You can use a regular expression. Haven't played with the syntax, so you will have to work on that.
preg_match('.txt', $string)
http://php.net/manual/en/function.preg-match.php

correct regex date pattern for dd/mm/yyyy

I need to update the same line, which is also including a date in dd/mm/yyyy format along with some string, in a group of files. I have checked answers here given to similar questions however couldn’t make any of the patterns suggested run in my code.
My current PHP code is:
<?php
// get the system date
$sysdate = date("d/m/Y");
// open the directory
$dir = opendir($argv[1]);
$files = array();
// sorts the files alphabetically
while (($file = readdir($dir)) !== false) {
$files[] = $file;
}
closedir($dir);
sort($files);
// for each ordered file will run the in the clauses part
foreach ($files as $file) {
$lines = '';
// filename extension is '.hql'
if (strpos($file,".hql") != false || strpos($file,".HQL") != false)
{
$procfile = $argv[1] . '\\' . $file;
echo "Converting filename: " . $procfile . "\n";
$handle = fopen($procfile, "r");
$lines = fread($handle, filesize($procfile));
fclose($handle);
$string = $lines;
// What are we going to change runs in here
$pattern = '[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]';
$replacement = $sysdate;
$lines = preg_replace($pattern, $replacement, $string);
echo $lines;
$newhandle = fopen($procfile, 'w+');
fwrite($newhandle, $lines);
fclose($newhandle);
// DONE
}
}
closedir($dir);
?>
When I run this code on command prompt, it doesn’t give any error message and it seems to be running properly. But once it finishes and I check my files, I see that the content of each file is getting deleted and they all become 0 KB files with nothing in them.
You have no delimiters set in place for your regular expression.
A delimiter can be any (non-alphanumeric, non-backslash, non-whitespace) character.
You want to use a delimiter besides / so you avoid having to escape / already in your pattern.
You could use the following to change your format:
$pattern = '~[0-9]{4}/[0-9]{2}/[0-9]{2}~';
See Live demo
This one also do basic checks (month between 1-12, day between 1-31)
(0(?!0)|[1-2]|3(?=[0-1]))\d\/(0(?!0)|1(?=[0-2]))\d\/\d{4}
See it live: http://regex101.com/r/jG9nD5
You should surround the regular expression with delimiter character.
For example:
$pattern = '![0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]!';
/ is commonly used, but because the regular expression contains / itself, I used ! instead.
Besides the lack of delimiters (# and ~ are favorites, if / is used in the pattern), you are looking for 4 digits at the beginning: yyyy/mm/dd. Decide what you're looking for. You might also be able to do something like
[0-9]{4}/[0-9]{2}/[0-9]{2}
or even
\d{4}/\d{2}/\d{2}
... I know those will work in Perl, but I haven't tried them with PHP (they ought to work, as the "p" in preg stands for Perl, but no guarantees).
Why use regex? Use DateTime class for validation.
var_dump(validateDate('2012-02-28', 'Y-m-d')); # true
var_dump(validateDate('28/02/2012', 'd/m/Y')); # true
var_dump(validateDate('30/02/2012', 'd/m/Y')); # false
function
Your code can be rewritten in short like this:
#!/usr/bin/php
<?php
// get the system date
$sysdate = date('d/m/Y');
// change working directory to the specified one
chdir($argv[1]);
// loop over the *.hql files in sorted order
foreach (glob('*.{hql,HQL}', GLOB_BRACE) as $file) {
echo "Converting filename: $argv[1]\\$file\n";
$contents = file_get_contents($file);
$contents = preg_replace('#\d{4}/\d{2}/\d{2}#', $sysdate, $contents);
echo $contents;
file_put_contents($file, $contents);
}
The problem was with the missing PCRE regex delimiters as others already pointed out. Even after fixing this, the code was not really nice.
The glob and file_get_contents functions are available as of PHP 4.3.0. The file_put_contents function is available as of PHP 5.
glob makes your code more succinct, readable and even portable as you won‘t have to mention directory separator anywhere except the info message. You used \\ but should have used DIRECTORY_SEPARATOR if you wanted your code to be portable.
The file_get_contents function fetches the whole contents of a file as a string. The file_put_contents function does the opposite – stores a string in a file. If you want it in PHP 4, use this implementation:
if (!function_exists('file_put_contents')):
function file_put_contents($filename, $data) {
$handle = fopen($filename, 'w');
$result = fwrite($handle, $data);
fclose($handle);
return $result;
}
endif;
Also notice that the final ?> is not necessary in PHP.

Categories