Excluding file extensions from my preg_match - php

I have a script I am using to filter some ROM and ISO files.
I have (with a lot of help) got a working script where files are filtered by filename, however I am trying to add a section in which I can include extra ad-hoc filenames to be filtered for me by providing them in a local .txt file. This is working OK, however in my .txt file I am having to put the full filename (including the .txt extension) into the .txt - for example my "manualregiondupes.txt file looks like this:
Game One.zip
Game Two.zip
Game Three.zip
Whereas I want it to just type them in my .txt file like so:
Game One
Game Two
Game Three
The current regex i'm using is trying to match the full filename it finds (including the .zip extension) whereas I want it to just match the section before the file extension. I have to be careful, however - as I don't want a game like:
"Summer Heat Beach Volleyball (USA)" being matched if "Beach Volleyball (USA)" is in the .txt.
Same goes for words on the other side - like
"Sensible Soccer (USA) (BETA)" being matched if "Sensible Soccer (USA)" is in the .txt
Here is my script;
// Make sure what manualregiondupes.txt is doing
if (file_exists('manualregiondupes.txt'))
{
$manualRegionDupes = file('manualregiondupes.txt', FILE_IGNORE_NEW_LINES);
$manualRegionPattern = "/^(?:" . implode("|", array_map(function ($i)
{
return preg_quote(trim($i) , "/");
}
, $manualRegionDupes)) . ')$/';
echo "ManualRegionDupes.txt has been found, ";
if (trim(file_get_contents('manualregiondupes.txt')) == false)
{
echo "but is empty! Continuing without manual region dupes filter.\n";
}
else
{
echo "and is NOT empty! Applying the manual region dupes filter.\n";
}
}
else
{
echo "ManualRegionDupes.txt has NOT been found. Continuing without the manual region dupes filter.\n";
}
// Do this magic for every file
foreach ($gameArray as $thisGame) {
if (!$thisGame) continue;
// Probably already been removed
if (!file_exists($thisGame)) continue;
// Filenames in manualregiondupes.txt
if (file_exists('manualregiondupes.txt'))
{
if (trim(file_get_contents('manualregiondupes.txt')) == true)
{
if (preg_match($manualRegionPattern, $thisGame))
{
echo "{$thisGame} is on the manual region dupes remove list. Moved to Removed folder.\n";
shell_exec("mv \"{$thisGame}\" Removed/");
continue;
}
}
}
... SCRIPT CONTINUES HERE BUT ISN'T RELEVANT!
What's the easiest way of doing this? I think i've just asked a very long question when it's actually quite simple, but oh well - I am not very good with PHP (or any script to be honest!) so apologies and thankyou's in advance! :D

You can use pathinfo in regex like -
$withoutExt = preg_replace('/\.' . preg_quote(pathinfo($path, PATHINFO_EXTENSION), '/') . '$/', '', $path);
it gives you perfect file name output without extension for
file.txt -> file
file.sometext.txt -> file.sometext

Related

Get full path from filename in php

So I have a URL which contains &title=blabla
I know how to extract the title, and return it. But I've been searching my ass off to get the full path to the filename when I only have the filename.
So what I must have is an way to search in all directories for an html file called 'blabla' when the only thing it has is blabla. After finding it, it must return the full path.
Anyone who does have an solution for me?
<?php
$file = $_GET['title'];
if ($title = '') {
echo "information.html";
} else {
//here it must search for the filepath and echo it.
echo "$filepath";
}
?>
You can use the solution provided here.
It allows you to recurse through a directory and list all files in the directory and sub-directories. You can then compare to see if it matches the files you are looking for.
$root = '/'; // directory from where to start search
$toSearch = 'file.blah'; // basename of the file you wish to search
$it = new RecursiveDirectoryIterator($root);
foreach(new RecursiveIteratorIterator($it) as $file){
if($file->getBasename() === $toSearch){
printf("Found it! It's %s", $file->getRealPath());
// stop at the first match
break;
}
}
Keep in mind that depending on the number of files you have, this can be slow as hell
For a start this line is at fault
if ($title = '') {
See http://www.php.net/manual/en/reserved.variables.files.php

php check if file exist: check only portion

in php we can check if file exist using
if(file_exists("destination/"))
{
condition
}
but what I wanted to do is...
for example I already have this file on my destination
hello_this_is_filename(2).doc
how would I know if there is a file in that directory having a name containing a character
hello_this_is_filename
I wanted to search that way because... if there is exists on that directory, what will I do is... renaming the file into
hello_this_is_filename(3).doc
I also need to count the existence of my search so I know what number I'm going to put like
(3), (4), (5) and so on
any help?
Use glob.
if (count(glob("destination/hello_this_is_filename*.doc"))) {
//...
}
Leveraging Marc B's suggestion and xdazz, I would do something as follows:
<?php
$files = glob("destination/hello_this_is_filename*");
if (count($files)) {
sort($files);
// last one contains the name we need to get the number of
preg_match("([\d+])", end($files), $matches);
$value = 0;
if (count($matches)) {
// increment by one
$value = $matches[0];
}
$newfilename = "destination/hello_this_is_filename (" . ++$value . ").doc";
?>
Sorry this is untested, but thought it provides others with the regexp work to actually do the incrementing...

Delete dir with non english characters in PHP

I have a function that is scanning dirs on server, read files, do something with it , and then deletes the dirs (nested)
The function is quite long , So I will post the relevant part .
//many other things ...
$dir_to_delete[] = $filename['dirname']; // the array to hold all the dirs.
} // end for each
$dir_to_delete_clean = array_unique($dir_to_delete); //clean array - we might have duplicated dir names
foreach ($dir_to_delete_clean as $delete) {
o99_deleteDirectory($delete) ;
}
// rmdir( $filename['dirname'] );
return $attc_id;
}
this is the delete function for non-empty dirs:
function o99_deleteDirectory($dir) {
if (!file_exists($dir)) return true;
if (!is_dir($dir)) return unlink($dir);
foreach (scandir($dir) as $item) {
if ($item == '.' || $item == '..') continue;
if (!o99_deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) return false;
}
return rmdir($dir);
}
It works great .
the problems is - when I checked for NON english characters ( German, Chinese, Hebrew, Arab, Cyrillic - or any other) - the script fails and stops...
I then tried rename() , rmdir() etc. - they all fail.
Is this a PHP bug ?
How can I resolve the problem ? I can not even rename them to later delete 8because rename() fails as well...
Any Ideas ??
Edit I
I forgot to mention that it is for wordpress plugin - but I would assume that it makes no difference...
Edit II
I am posting here some languages if someone wants to try but do not have the right keyboard / language settings . I am not sure that cutting and pasting will give the right encoding, but can always try ...
עברית (hebrew)
中國的 (chinese traditional)
عربي (arabic)
кириллица (cyrillic)
ελληνικά (greek)
öäüìíáàóò´Ä´` (German-Italian-Spanish and other european)
Have you tried to set locale before scanning or removing directories.
http://www.php.net/manual/en/function.setlocale.php
I have not tried this but you can give it a shot. It might help.

how to scan all usages of a custom function in all my php files?

I have created my own l($text) function in php for a multi lingual website. i use it like this in my documents :
echo '<h1>' . l('Title of the page') . '</h1';
echo '<p>' . l('Some text here...') . '</p>';
My question is, with a php script, how can i scan all my .php files to catch all this function usages and list all the arguments used into a mysql table?
the goal, of course, is to not forget any sentences in my traduction files.
I didn't find anything on google or here, so if you have any ideas, or need some more information.
Could you:
read all *.php files with glob()
then use a regex to pull the strings out (preg_match())
strings simple mysql insert?
Seems simple enough?
i just finished, your help was usefull ! :-)
here is my ugly code for those who can be interested. it's not beautifuly coded, but not made to be loaded 10000 times per day so...
<?php
// define a plain text document to see what appen on test
header('Content-Type: text/plain; charset=UTF-8');
$dossier = 'pages/'; // folder to scan
$array_exclude = array('.', '..', '.DS_Store'); // system files to exclude
$array_sentences_list = array();
if(is_dir($dossier)) // verify if is a folder
{
if($dh = opendir($dossier)) // open folder
{
while(($file = readdir($dh)) !== false) // scan all files in the folder
{
if(!in_array($file, $array_exclude)) // exclude system files previously listed in array
{
echo "\n".'######## ' . strtoupper($file) . ' ##########'."\n";
$file1 = file('pages/'.$file); // path to the current file
foreach($file1 AS $fileline)
{
// regex : not start with a to z characters or a (
// then catch sentences into l(' and ')
// and put results in a $matchs array
preg_match_all("#[^a-z\(]l\('(.+)'\)#U", $fileline, $matchs);
// fetch the associative array
foreach($matchs AS $match_this)
{
foreach($match_this AS $line)
{
// technique of "I do not want to break my head"
if(substr($line, 0, 3) != "l('" AND substr($line, 0, 4) != " l('" AND substr($line, 0, 4) != ".l('")
{
// check if the sentence is not already listed
if(!in_array($line, $array_sentences_list))
{
// if not, add it to the sentences list array and write it for fun !
$array_sentences_list[] = $line;
echo $line . "\n";
}
}
}
}
}
}
}
closedir($dh);
}
}
?>
small precision : i do have to escape various cases as :
-> CSS : background: url('image.jpg');
and
-> jQuery : $(this).html('bla bla');
so here is why the regex starts with [^a-z(] :-)
it works very well now! just have to finish later with recording entries in a mysql table and ensure that i can load the script from time to time when there are changes on the site... keep the existing translation, overwrite the existing files etc... no problem with that.
thanks a gain, this website is really helpful ! :-)

Browsing local directories and files with php

Instead of the traditional navigation, I am trying to emulate the terminal navigation, or how you navigate with vim.
Example:
..
index
otherfile
This is my code:
$dir = realpath(dirname(__FILE__));
if(is_dir($dir)){
if($open = opendir($dir)){
while(($file = readdir($open)) !==false){
if(is_dir($file)){
if($file == '.'){ }
else{
echo "".$file."<br/>";
}
}
else{
$name = explode('.php',$file);
echo "".$name[0]."<br/>";
}
}
}
}
else{
echo $dir." Was not found";
}
}
How can I remove the file or folder I am in from the list? For example, if I am on the page index.php, it is still appearing on the list.
I want to sort files by given them a number example '1file.php' '2anotherfile.php'..
How could I sort them by the number, then remove the number and '.php', and finally print it out?
If you feel like refactoring something please do so...
"How can I remove the file or folder I am in from the list? For example, if I am on the page index.php, it is still appearing on the list."
Just check if the current item is the current file, if it is then skip it:
else {
if ($name == basename(dirname(__FILE__))) continue; // if this is the current file, go to the next iteration of the loop
$name = explode('.php',$file);
echo "".$name[0]."<br/>";
}
Note that this assumes you are in the same directory as the file (which it can do because $dir is always the directory the script is in), if not you can just add a directory check as well.
"How can add a number to the start of the file or folder, example 1index.php, then on the code, organize all the files and folder by number, and print them without the number and '.php'?"
Well I'm not too sure what you mean by this, but if you mean sort alphabetically, then it is already alphabetically sorted when you get the list.

Categories