MAC OSX creates some unwanted dot underscore files to store file information.
There are currently two files in a directory on my file system - Test.php and ._Test.php.
I need to write a preg_match to accept only first file and ignore the metadata file. For eg.
preg_match('/^(.+)\.php$/', $fileName, $matches);
But, here $matches returns the same output for both $fileName = Test.php and ._Test.php.
Is there anyway to modify the regex to ignore the metadata file and accept only Test.php?
Use a negative lookahead to assert that the string doesn't start with ._:
^(?!\._)(.+)\.php$
Demo
PHP sample
<?php
$tests[] = "Test.php";
$tests[] = "._Test.php";
$tests[] = ".Testing.php";
$tests[] = "_Testing2.php";
$tests[] = "._greajo.com";
$tests[] = "_.greajo.com";
foreach ($tests as $test) {
if (preg_match("/^(?!\._)(.+)\.php$/i", $test, $m)) {
echo "Valid file: ".$m[1].PHP_EOL;
}
else {
echo "Invalid file".PHP_EOL; // discard?
}
}
Demo
Result
Valid file: Test
Invalid file
Valid file: .Testing
Valid file: _Testing2
Invalid file
preg_match('/^[^\.].*\.php$/', $fileName, $matches);
See demo https://implode.io/evnXDC
Related
I'm trying to search all of the files in a directory instead of one, but I don't know what to use to do that.
results.php:
<?php
// error_reporting(E_ERROR | E_PARSE);
$file = 'db/test.txt';
$searchfor = $_GET['q'];
if (!$_GET['q']) { // returns this if query is empty
echo "Search something.";
}
else {
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if (preg_match_all($pattern, $contents, $matches))
{
echo "<centerResults</center><br>";
echo "<pre>";
echo implode($matches[0]);
echo "</pre>";
}
else
{
echo "<center>No results</center>";
}
}
I wanted to do something like this on line 3:
$file = 'db/*';
So that it could search through test.txt, and other txt files in that directory.
And i've tried googling, and nothing helpful has come up, any help?
Ther is function called glob it accept a required parameter which is the path and it can be a pattern of the files and it return an array of the paths of all the files that match that pattern .
in other words , you can use this function with "dir/*.txt" and it is going to return all the files that ar in the dir folder and has the txt extension
I am using a simple php translation class and I have about more than 2000 php files which the translation class was implemented and new strings are as well implemented so I need an updated text file with all the translation strings.
I need to get all the translated values from each php file and save it into a text file without any repeated value.
Translation class
<?php $translate->__('Calendar'); ?>
So I need to get Calendar saved into a txt file and this should be done for all the files in all folders.
Everything in between $translate->__(' and ') should be saved.
The below code not working for some reason.
$fn = $_SERVER['DOCUMENT_ROOT']."/apps/test/test2/calendar.php";
$handle = fopen($fn, 'r');
$valid = false;
$search = "\/\\$translate\\-\\>__\\(\\'(.*?)'\\)\/g";
while (($buffer = fgets($handle)) !== false) {
if(preg_match_all($search, $buffer, $m)) {
print $m[1];
} else {
}
}
fclose($handle);
You're extracting strings with this pattern:
/\$translate\-\>__\(\'(.*?)'\)/g
extract all of matched items and save them any where.
Demo and Details : https://regex101.com/r/LzMyJY/1
$fn = $_SERVER['DOCUMENT_ROOT']."/apps/test/test2/calendar.php";
$handle = fopen($fn, 'r');
$valid = false;
$search = "/\\".'$'."translate\\-\\>__\\(\\'(.*?)'\\)/g";
while (($buffer = fgets($handle)) !== false) {
if(preg_match_all($search, $buffer, $m)) {
print $m[1];
} else {
}
}
fclose($handle);
Note:
In use of regex patterns, remember handle backslash \ when putting pattern in ".." (change all \ to \\ in this case)
If using '...' don't change \ with \\ !
I'm having issues using scandir with a variable sent through a function from preg_replace. I'm getting warning when I run the code PHP Warning: scandir(../dir/$1): failed to open dir: No such file or directory, however, when I echo $dir it echos it correctly with $1 expanded to the variable. Here's my code:
$str = preg_replace('/([0-9]{2})/', $this->functionName("$1"), $str);
private function functionName($year) {
$path = '../dir/'.$year;
echo $path; // echos 'dir/14'
$results = scandir($path); // claims $path is 'dir/$1'
}
Is there such a function in PHP that does grep -f filename in unix/linux systems.
If there is none, what PHP functions/tools would help in creating a customised method/function for this. Thanks!
Actually IMHO, I'd say it's the following:
$result = preg_grep($pattern, file($path));
See preg_grepDocs and fileDocs.
If you need to do that (recursively) over a set of files, there is also glob and foreach or the (Recursive)DirectoryIterator or the GlobIteratorDocs and not to forget the RegexIteratorDocs.
Example with SplFileObject and RegexIterator:
$stream = new SplFileObject($file);
$grepped = new RegexIterator($stream, $pattern);
foreach ($grepped as $line) {
echo $line;
}
Output (all lines of $file containing $pattern):
$grepped = new RegexIterator($stream, $pattern);
foreach ($grepped as $line) {
echo $line;
}
Demo: https://eval.in/208699
You can combine the file_get_contens() function to open a file and the preg_match_all() function to capture contents using a regex.
$file = file_get_contents ('path/to/file.ext');
preg_match_all ('regex_pattern_here', $file, $matches);
print_r ($matches);
I have a .txt file that holds a lot of forbidden words in a forum, with the expression like:
//filterwords.txt
XXX
YYY
ZZZ
and then, I would like to use preg_match to check incoming text $str with these words; if those forbidden words are not included, we can do something; otherwise, we do another thing... I am not sure about the expression, and I just know:-
$filter_word = file("filterwords.txt")
for ($i=0; $i< count($filter_word);$i++)
{
if(!preg_match($filter_word[$i],$str))
{
echo "not ok!";
exit;
}
else
{
echo "ok!!";
exit;
}
}
Could experts teach me how to write the preg_match part? thankyou.
How about this:
<?php
$file = file_get_contents('filterwords.txt');
$words = preg_split("#\r?\n#", $file, -1, PREG_SPLIT_NO_EMPTY);
#Added to escape metacharacters as mentioned by #ridgerunner
$words = array_filter("preg_quote", $words);
$pattern = "#\b(". implode('|', $words) . ")\b#";
if(preg_match($pattern, $str))
{
echo "bad word detected";
}
?>
P.S. That's assuming that you have the text to check in the $str var