How to find a substring of a string in an array PHP - php

If you look at many of my questions, you will see that sometimes I don't ask the best questions or I am in such a rush that I don't see the answer that is right in front of me the whole time. If this is another one of those questions, please be kind as some other people haven't been the nicest. Now onto the question.
I have been in the process of creating a file listing viewer type thing for the past week or so. At this point, its all great but I needed to add a search function. I did so by using array_search(). The only problem is that this function requires you to put in the EXACT name of the file rather than part of it.
Here is the problem. I have tried numerous solutions, and to be frank, my PHP skills aren't the most professional. I have tried for array_filters and for loops with strpos. Nothing at this point works. My code is below:
<?php
//error_reporting(0);
//ini_set('display_errors', 0);
//$dir = $_SERVER["DOCUMENT_ROOT"] . '/';
$dir = getcwd();
$files = $files = array_slice(scandir($dir), 2);
$number = count($files);
sort($files);
$images = array();
$an = count($images);
$query = $_GET['q'];
$searchimages = array();
$san = count($searchimages);
$r = array();
if ($query) {
for ($w = 0; $w <= $number; $w++){
$rnum = count($r);
if (strpos($files[$w], $query) !== false) {
$r[$rnum++] = $files[$w];
}
}
if ($r != null) {
if (substr($files[$r], -5) == ".jpeg" || substr($files[$r], -4) == ".png" || substr($files[$r], -4) == ".jpg" || substr($files[$r], -4) == ".gif") {
$searchimages[$san++] = $files[$r];
echo "<a href='#" . $files[$r] . "'>" . $files[$r] . "</a><br>";
} else {
echo "<a href='" . $files[$r] . "'>" . $files[$r] . "</a><br>";
}
for ($z = 0; $z <= $san; $z++)
echo "<a name='" . $searchimages[$z] . "'>" . "<a href='" . $searchimages[$z] . "' target='_blank'>" . "<img src='" . $searchimages[$z] . "'>" . "</img></a>";
} else {
echo "No results found. Please try a different search" . "<br>";
}
} else {
for ($x = 0; $x <= $number; $x++) {
if (substr($files[$x], -5) == ".jpeg" || substr($files[$x], -4) == ".png" || substr($files[$x], -4) == ".jpg" || substr($files[$x], -4) == ".gif") {
$images[$an++] = $files[$x];
echo "<a href='#" . $files[$x] . "'>" . $files[$x] . "</a><br>";
} else {
echo "<a href='" . $files[$x] . "'>" . $files[$x] . "</a><br>";
}
}
for ($y = 0; $y <= $an; $y++) {
echo "<a name='" . $images[$y] . "'>" . "<a href='" . $images[$y] . "' target='_blank'>" . "<img src='" . $images[$y] . "'>" . "</img></a>";
}
}
?>
Currently there are over 2,000 files and they have all sorts of random characters in them. These characters range from dashes to exclamation marks to letters and numbers as well as periods and many more. I don't have control over these file names and they have to stay exactly the same.
If you look at the code, I first get all the file names and store them in an array,
$files
Then I check if the search parameter is supplied in the url,
?q=insert-search-terms-here
After that, if it is supplied, I will search for it (this is where the problem is). If it isn't supplied, I simply get the file names from the array and check if they are an image. If they are, I print them all out at the bottom of the page in the form of thumbnails and make their link at the top a page link that scrolls you down to the location of the image. If it isn't an image, it takes you directly to the file. Note that the thumbnails are links to the actual image.
What is supposed to happen when it searches is that basically does what it would do if it weren't searching, but it limits itself to files that contain the string "foobar" for example.
When it searches but doesn't find anything, it prints out that it didn't find anything and that the user should search again.
If anyone could help with this, it would be greatly appreciated. Like I said at the beginning, please be kind if its a dumb mistake.
Best Regards,
Emanuel
EDIT:
This article now obviously has an answer and for those finding this article on Google or what have you, I want you to read the comments in the answer post as well as the answer as they provide KEY information!!

You may want to use preg_grep. Replace this:
for ($w = 0; $w <= $number; $w++){
$rnum = count($r);
if (strpos($files[$w], $query) !== false) {
$r[$rnum++] = $files[$w];
}
}
with this:
$r = preg_grep('/\Q' . $query . '\E/', $files);
Example:
$files = array(
'foo.bar',
'barfoo.baz',
'baz.fez',
'quantum-physics.ftw',
);
$query = 'foo';
$r = preg_grep('/\Q' . $query . '\E/', $files);
print_r($r);
Output:
Array
(
[0] => foo.bar
[1] => barfoo.baz
)
The preg_match below can be read "match any string ending with a dot followed by jpeg, png, jpg or gif" (the dollar sign can be translated into "end of the string").
if ($query) {
$r = preg_grep('/\Q' . $query . '\E/', $files);
if ($r != null) {
foreach($r as $filename) {
if (preg_match('/\.(jpeg|png|jpg|gif)$/', $filename)) {
// File is an image
echo "$filename is an image<br/>";
// Do stuff ...
} else {
// File is not an image
echo "$filename is NOT an image<br/>";
// Do stuff ...
}
}
// ... Do more
} else {
echo "No results found. Please try a different search" . "<br>";
}
}

http://www.wordinn.com/solution/108/php-getting-part-string-after-and-given-sub-string-or-character
this might be help ful..
function strafter($string, $substring) {
$pos = strpos($string, $substring);
if ($pos === false)
return $string;
else
return(substr($string, $pos+strlen($substring)));
}

Something like this will work even for associative array.
foreach ($members as $user){
$Match = substr($user['column'][0], strpos($user['column'][0], "#") + 1);
$final_Array[$i]=$Match;
$i++;
}
print_r($final_Array)

Related

conditional statement does not work even if the statement returns true for image captions

I am trying to write a conditional if statement to get image caption if number of images match number of captions in the db row
code does work without if statement but fails to execute even if the condition returns true.
php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$individual_files = explode("|", $row["images_names"]);
$individual_text = explode("_", $row["image_text"]);
for ($file_number = 0; $file_number < sizeof($individual_files) - 1; $file_number++) {
if( count($individual_files) == count($individual_text)) {
echo "<li>";
echo "<img src='Blog-Albums/" . $row["sno"] . "/" . $individual_files[$file_number] . "' alt='gallery image'/>";
echo "<div class='slider-caption'><p style='color:#ffffff'>this is sample file</p></div>";
echo "</li>";
} elseif ( count($individual_files) != count($individual_text)) {
echo "<li><img src='Blog-Albums/" . $row["sno"] ."/". $individual_files[$file_number] . "' alt='gallery image'/><div class='slider-caption'><p></p></div></li>";
}

Download link over random php image

I am displaying a number of random images from a folder, however I'm not very good with PHP (Code sourced from the internet), how would I go about having a "download" link display on top of the image?
Display random image from folder using PHP:
function random_image($directory)
{
$leading = substr($directory, 0, 1);
$trailing = substr($directory, -1, 1);
if($leading == '/')
{
$directory = substr($directory, 1);
}
if($trailing != '/')
{
$directory = $directory . '/';
}
if(empty($directory) or !is_dir($directory))
{
die('Directory: ' . $directory . ' not found.');
}
$files = scandir($directory, 1);
$make_array = array();
foreach($files AS $id => $file)
{
$info = pathinfo($dir . $file);
$image_extensions = array('jpg', 'jpeg', 'gif', 'png', 'ico');
if(!in_array($info['extension'], $image_extensions))
{
unset($file);
}
else
{
$file = str_replace(' ', '%20', $file);
$temp = array($id => $file);
array_push($make_array, $temp);
}
}
if(sizeof($make_array) == 0)
{
die('No images in ' . $directory . ' Directory');
}
$total = count($make_array) - 1;
$random_image = rand(0, $total);
return $directory . $make_array[$random_image][$random_image];
}
Markup:
echo "<img src=" . random_image('css/images/avatars') . " />";
I've tried looking around google for an answer but I can't find anything, any help would be appreciated
You should save the image location in a variable then use it to create a link, plus display it.
$imageUrl = random_image('css/images/avatars');
echo "<a href=" . $imageUrl . ">";
echo "<img src=" . $imageUrl . " />";
echo "</a>";
or if you want to show the text link above, seperately then
$imageUrl = random_image('css/images/avatars');
echo "Click Here<br />";
echo "<img src=" . $imageUrl . " />";
you could use simple javascript to do so, like onclick event for example :
just add this to img tag onclick='window.open('". random_image('css/images/avatars') ."')'
echo "<img onclick='window.open('". random_image('css/images/avatars') ."')' src='" . random_image('css/images/avatars') . "' />";

Wrap Output in Properly Nested Lists - PHP Directory Listing

Okay, I've been searching for a way to list directories and files, which I've figured out and am utilizing code I found here on StackOverflow (Listing all the folders subfolders and files in a directory using php).
So far I've altered code found in one of the answers. I've been able to remove file extensions from both the path and the file name using preg_replace, capitalize the file names using ucwords, and switch out dashes for spaces using str_replace.
What I'm having trouble with now is wrapping the whole thing in a properly nested HTML list. I've managed to set it up so it's wrapped in a list, but it doesn't use nested lists where needed and I can't, for the life of me, figure out how to capitalize the directory names or replace any dashes within the directory name.
So, the questions are, if anyone would be so kind:
How do I wrap the output in properly nested lists?
How do I capitalize directory names while removing the preceding slash and replace dashes or underscores with spaces?
I've left the | within the $ss variable intentionally. I use it as a marker of sorts when I want to throw in characters that will identify where it shows up during trial and error (example $ss = $ss . "<li>workingOrNot").
I'm using:
<?php
$pathLen = 0;
function prePad($level) {
$ss = "";
for ($ii = 0; $ii < $level; $ii++) {
$ss = $ss . "| ";
}
return $ss;
}
function dirScanner($dir, $level, $rootLen) {
global $pathLen;
$filesHidden = array(".", "..", '.htaccess', 'resources', 'browserconfig.xml', 'scripts', 'articles');
if ($handle = opendir($dir)) {
$fileList = array();
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".." && !in_array($entry, $filesHidden)) {
if (is_dir($dir . "/" . $entry)) {
$fileList[] = "F: " . $dir . "/" . $entry;
}
else {
$fileList[] = "D: " . $dir . "/" . $entry;
}
}
}
closedir($handle);
natsort($fileList);
foreach($fileList as $value) {
$displayName = ucwords ( str_replace("-", " ", substr(preg_replace('/\\.[^.\\s]{3,5}$/', '', $value), $rootLen + 4)));
$filePath = substr($value, 3);
$linkPath = str_replace(" ", "%20", substr(preg_replace('/\\.[^.\\s]{3,5}$/', '', $value), $pathLen + 3));
if (is_dir($filePath)) {
echo prePad($level) . "<li>" . $linkPath . "</li>\n";
dirScanner($filePath, $level + 1, strlen($filePath));
} else {
echo "<li>" . prePad($level) . "" . $displayName . "</li>\n";
}
}
}
}
I feel like these answers should be simple, so maybe I've been staring at it too much the last two days or maybe it has become Frankenstein code.
I'm about out of trial and error and I need help.
foreach($fileList as $value) {
$displayName = ucwords ( str_replace("-", " ", substr(preg_replace('/\\.[^.\\s]{3,5}$/', '', $value), $rootLen + 4)));
$filePath = substr($value, 3);
$linkPath = str_replace(" ", "%20", substr(preg_replace('/\\.[^.\\s]{3,5}$/', '', $value), $pathLen + 3));
if (is_dir($filePath)) {
// Do not close <li> yet, instead, open an <ul>
echo prePad($level) . "<li>" . $linkPath; . "<ul>\n";
dirScanner($filePath, $level + 1, strlen($filePath));
// Close <li> and <ul>
echo "</li></ul>\n";
} else {
echo "<li>" . prePad($level) . "" . $displayName . "</li>\n";
}
}
I guess you're opening the main before call the function and closing it at the end.

How to print just a few from an array instead of all in php

This is part of the working code that shows the entire array;
$files = filelist("./",1,1); // call the function
shuffle($files);
foreach ($files as $list) {//print array
echo "<h4> " . $list['name'] . " </h4>";
// echo "Directory: " . $list['dir'] . " => Level: " . $list['level'] . " => Name: " . $list['name'] . " => Path: " . $list['path'] ."<br>";
How do I modify it so that it only displays 10 or 15 list instead of all?
Use a counter to limit the number of iterations:
$counter = 0;
foreach ($files as $list) {//print array
// your loop code here...
$counter++;
if ($counter > 10) break;
}
If you know the keys or indexes of the array you can do what KingCrunch is doing a lot faster by simple for loop
for($i=0; $i<=14; $i++) {
// echo $file[$i];
}
There is a function for it
foreach(array_slice($files, 0, 15) as $file) {
/* your code here */
}
http://php.net/array-slice
Another solution is to use array_rand() instead of shuffle() and array_chunk()
foreach (array_rand($files, 15) as $key) {
$file = $files[$key];
// Your code here
}
http://php.net/array-rand
Note, that this keeps the order of the keys (see salathes comment below).

Image doesn't appear

I'm new to PHP and I have this homework to do. The teacher asked us to display a greeting message to the user which should look like:
Good(Morning/Evening/Night), username, actual date(taken from the system).
PHP:
$username = "Foo";
if (date("H") > 0 && date("H") < 12) {
$msg = "Good day";
$image = "r_sun";
}
else if (date("H") >= 12 && date("H") < 18) {
$msg = "Good evening";
$image = "sun";
}
else {
$msg = "Good Night";
$image = "moon";
}
if (date("d") == 1) {
$c = "st";
}
else if (date("d") == 2) {
$c = "nd";
}
else if (date("d") == 3) {
$c = "rd";
}
else {
$c = "th";
}
echo $msg . "<img src='images/" . $image . ".png' border='0' />, " . $username . "! Today is " . date("F") . " " . date("d") . $c . ", " . date("Y");
My problem is with the image. I have to show 3 different images depending on which message is being displayed (Good morning, evening or night). For some reason the image won't load on the page.
You have to add ../ before the images path on your src attribute like this:
<img src='../images/" . $image . ".png' border='0' />
This means that your image path is not on the same directory as your script, like you doing.
Plus, just a tip, place the date values on an variable:
$h = date("H");
$d = date("d");
if ($h > 0 && $h < 12) {
$msg = "Good day";
$image = "r_sun";
}
if ($d== 1) {
$c = "st";
}
Will clear your code ;)
Based on your comment above:
my code is on the path www/admin and the images are in www/images
It sounds like the img tag just needs a slight adjustment. Try this:
echo $msg . "<img src='../images/" . $image . ".png' border='0' />, " . $username . "! Today is " . date("F") . " " . date("d") . $c . ", " . date("Y");
The key difference is adding the ../ to the start of the path. This is a relative path designation which tells the browser to go up one directory before looking for the path/file specified.
Note that this isn't an issue with the PHP code specifically. The code was correctly emitting a valid img tag. The problem was that the path was pointing to a file that doesn't exist (www/admin/images/filename) instead of one that does (www/images/filename).
The way you've specified your img src, the images must exist in the same directory as your script (or your basehref if you've set that in the html head). Check that first.
Secondly, check the permissions of the images directory. It must be at least world-executable (0711).
Thirdly, check the permissions of the image files. They must be at least world-readable (0644).

Categories