dongningce9075 2015-03-01 20:36
浏览 48
已采纳

如何在数组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!!

  • 写回答

2条回答 默认 最新

  • doulingqiu4349 2015-03-01 21:03
    关注

    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>";
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度