Here's what I need, I have files: "page-Home1.php", "page-Contact2.php".
Yes I understand they don't have beautiful names but that's not what I'm worrying about right now, what I need is for glob to echo the files in order by 1,2,3 etc..
I currently have:
<?php
foreach (glob("page-*") as $filename) {
$result = str_replace("page-","", $filename);
$result = str_replace(".php","", $result);
echo "<li><a href='" . $filename ."'/>". $result . "</a></li><tr>";
}
?>
Though that only spits them out in a random order, I need it to number order.... Any ideas?
$files = glob(dirname(__FILE__).'/page-*.php');
foreach ($files as $file) {
$result[preg_replace('#[^0-9]#','', $file)]['file'] = $file;
$result[preg_replace('#[^0-9]#','', $file)]['name'] = str_replace(array("page-", ".php"), array('', ''), $file);;
}
sort($result);
foreach($result as $data) {
echo $data['file'].' -> '.$data['name'].'<br>';
}
Sort your array before iterating over it.
Related
I am have retrieved all the file contents from a directory. It prints the file contents name from an array. However I want only a portion of the file content name. Any idea how can I achieve this? I have tried using the following:
The file contents from the directory has format: pdb101m.ent.gz , pdb102l.ent.gz
I want to retrieve only the 101m and 102l
<?php
$dir = "C:/Users/Desktop/EAD/PDB/";
$files = array();
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
foreach($files as $ex){
echo str_replace('pdb.ent.gz', ' ', $ex). '<br>';
}
?>
Please help. Grateful.
Use substr() function:
echo substr('pdb101m.ent.gz',3,4); // Outputs: 101m
echo substr('pdb102l.ent.gz',3,4); // Outputs: 102l
So:
foreach($files as $ex){
echo substr($ex, 3,4). '<br>';
}
Edit: Update my answer attending the OP new request:
So in your query you should use:
foreach ($files as $ex) {
$search = substr($ex, 3, 4);
$sql = 'SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` <> "' . $search . '" LIMIT 6';
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$pdb[] = $row['pdb_code'];
}
}
If it's always pdb at the beggining and .ent.gz at the end you can do simply:
echo substr('pdb101m.ent.gz',3,-7);
Negative value of third parameter in substr() means
that many characters will be omitted from the end of string
I'm facing some problem with php regex but after many researches (conditional regex, subpattern regex), I still can't solve it.
I have a folder that contains many images and based on variable value I have to go to that folder and select all images that match the value.
e.g: In my folder I have 3 images:
p102.jpg ; p1020.jpg ; p102_1.jpg;
I only want the regex to select :
p102.jpg ; p102_1.jpg
but with the regex below It selects all 3 images.
$image_to_find = 102;
$path = "[^\d]*.*/"
$test = "/^[a-zA-Z]?$image_to_find".$path;
foreach(glob($file_directory) as $file){
if(preg_match($test, $file)){
match[]= $file;
}
}
I also try:
$path = "(?:\_[0-9]?).*/"; (it selects only p102_1.jpg)
Can you help me to figure it out. thanks
(sorry for the english)
You can avoid the foreach loop if you use the glob pattern:
$num = 102;
$result = glob($path . '[a-zA-Z]' . $num . '[._]*');
Note: if you need to allow several different formats, you can use array_merge and several glob patterns: array_merge(glob(...), glob(...));
If you want the first letter optional:
$result = array_merge(
glob($path . $num . '[._]*jpg'),
glob($path . '[a-zA-Z]' . $num . '[._]*jpg')
);
or better, use the brace option:
$result = glob($path . '{[a-zA-Z],}' . $num . '[._]*jpg', GLOB_BRACE);
That stays a better alternative than the combo "foreach/preg_match" (or preg_grep) if filenames are not too complicated.
With preg_grep:
$pattern = '~(?:^|/)[a-z]?' . $num . '(?:_\d+)?\.jpg$~i';
$result = preg_grep($pattern, glob($path . '*' . $num . '*.jpg'));
Try this:
/p102[_\.]\d*\.?jpg/g
https://regex101.com/r/hM4oE0/1
Where p102 should be your 'image_to_find' var.
Not tested, should work.
$find = 102;
$pattern = "/p". $find ."(?:_\d+)?\.jpg/";
$list = array();
foreach (glob($file_directory) as $file)
{
if (preg_match($pattern, $file))
{
$list[] = $file;
}
}
regex: http://regexr.com/3bp29
Tested and working:
<?php
$image_to_find = 102;
$pattern = '[a-zA-Z]' . $image_to_find . '[._]*';
$path = '/your_folder/your_subfolder/';
$file_directory = glob($path . $pattern );
echo '<pre>';
var_dump($file_directory);
echo '</pre>';
exit();
I hope this helps!
I have the next code:
<?php
$path = 'imgsFor';
$files_array = scandir($path);
for ($x=0; $x<=4; $x++)
{
echo '<img src="imgsFor/$files_array[$x]" <br>';
}
?>
In order to display all images in the folder imgsFor.
For some reason, I see the just boxes and not the actual images.
What can be the reason?
The best way for me is to use glob function:
foreach (glob($path) as $filename) {
echo '<img src="' . $path . '/' . $filename . '"/><br/>';
}
You messed up some things. Your correct script would be
<?php
$path = 'imgsFor/';
$files_array = scandir($path);
foreach($files_array as $f) {
if(is_dir($path . $f) === false)
continue;
echo '<img src="' , $path , $f , '"><br>';
}
/* EOF */
The reason is that your URL is invalid. Your variable wont echo out if you use single quotes. You also forgot to end the tag. Try this:
echo "<img src='http://yourwebsite.com/imgsFor/{$files_array[$x]}'/><br/>";
Please check you directory path and use is_dir which returns false when the file doesn't exist. you can try like this
$path = 'imgsFor';
$scan = scandir($path);
foreach($scan as $file)
{
if (!is_dir($path))
{
echo $file.'\n';
}
}
I have the following code which outputs the contents of text files held in a directory.
Ive been looking at the sort command in PHP but cant get it to work with the following code, I usually get an error about the input being a string and not an array.
How can I sort the directory of file before they are output?
$directory = "polls/";
$dir = opendir($directory);
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if ($type == 'file') {
$contents = file_get_contents($filename);
list($tag, $name, $description, $text1, $text2, $text3, $date) = explode('¬', $contents);
echo '<table width="500" border="1" cellpadding="4">';
echo "<tr><td>$tag</td></tr>\n";
echo "<tr><td>$name</td></tr>\n";
echo "<tr><td>$description</td></tr>\n";
echo "<tr><td>$text1</td></tr>\n";
echo "<tr><td>$text2</td></tr>\n";
echo "<tr><td>$text3</td></tr>\n";
echo "<tr><td>$date</td></tr>\n";
echo '</table>';
}
}
closedir($dir);
First collect the entries in an array, sort it and then put it out:
$directory = "polls/";
$dir = opendir($directory);
$files = array();
while (($file = readdir($dir)) !== false) {
$files[] = $file;
}
closedir($dir);
sort($files);
foreach ($files as $file) {
// content of your original while loop
}
Another possibility is fetching the file names with glob(). Its output is sorted by default.
<?php
foreach(glob('polls/*.txt') as $file){
// ...
}
?>
Don't print it in the while loop, but store it in an array. Sort the array and then print it.
(On php.net you'll find enough different sorting functions to get the sorting method you need.)
I have the following code, which will retrieve a filename from a table and make a link to it. What I want to do, is have it so I can refer to $filesList later on, and it will contain a single block of html code with links to as many files as there are files.
I thought adding to the previous variable would be the easiest way to do this, but it actually outputs nonsense code: 0test.sh">test.sh
if ($getFiles = $con->prepare($filesQuery)) {
$getFiles->bind_param("s", $pk);
$getFiles->execute();
$getFiles->bind_result($FILENAME);
$files = array();
while ($getFiles->fetch()) {
$filename = array(
'FILENAME' => $FILENAME,
);
$files[] = $filename;
}
}
$filesList = '';
foreach ($files as $filenames)
{
$filesList = $filesList + '<p>'. $filenames['FILENAME'] .'' . "\n";
};
Sureley I do not need to have an array for what i want to do?
You need to change that code to:
$filesList = '';
foreach ($files as $filenames)
{
$filesList .= '<p>'. $filenames['FILENAME'] ."</p>\n";
};
Does that help? You cannot concatenate with +.
One thing that I immediately spot is that you have $filesList = $filesList + ... Use a dot and not a + -sign.
Try this
$filesList = $filesList . "<p>{$filenames['FILENAME']}";
Have you tried something like this?
(Untested code, as I am not at home)
if ($getFiles = $con->prepare($filesQuery)) {
$getFiles->bind_param("s", $pk);
$getFiles->execute();
$getFiles->bind_result($FILENAME);
$files = array();
while ($getFiles->fetch()) {
$filesList = $filesList + '<p>'. $FILENAME .'' . "\n";
}