简体   繁体   English

如何在数组 PHP 中查找字符串的子字符串

[英]How to find a substring of a string in an array 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().我是通过使用 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.我尝试了很多解决方案,坦率地说,我的 PHP 技能并不是最专业的。 I have tried for array_filters and for loops with strpos.我已经尝试过使用 strpos 进行 array_filters 和 for 循环。 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.目前有超过 2,000 个文件,其中包含各种随机字符。 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,然后我检查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.搜索时应该发生的事情是,如果它不搜索,它基本上会做它会做的事情,但它会将自己限制在包含字符串“foobar”的文件中,例如。

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!!编辑:这篇文章现在显然有一个答案,对于那些在谷歌上找到这篇文章或你有什么的人,我希望你阅读答案帖子中的评论以及答案,因为它们提供了关键信息!!

http://www.wordinn.com/solution/108/php-getting-part-string-after-and-given-sub-string-or-character this might be help ful.. http://www.wordinn.com/solution/108/php-getting-part-string-after-and-given-sub-string-or-character这可能会有所帮助..

function strafter($string, $substring) {
  $pos = strpos($string, $substring);
  if ($pos === false)
   return $string;
  else 
   return(substr($string, $pos+strlen($substring)));
}

You may want to use preg_grep .您可能想使用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").下面的preg_match可以读作“匹配任何以点结尾的字符串,后跟 jpeg、png、jpg 或 gif”(美元符号可以翻译成“字符串的结尾”)。

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>";
    }
}

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM