如何从数组输出中删除垃圾数据

Soh*_*nar 5 php sql arrays laravel

我在服务器上插入多个图像,并使用(,)分隔使用SQL Server在其中存储名称。

if($request->hasFile('images')){
     $images= [];
        foreach($images=$request->file('images') as $img) {
             $name=$img->getClientOriginalName();
             $img->move(public_path().'/dpic', $name);    

            $images[]=$name;
        }

    }
            $test =implode(", ", $images);   
            $product->images  =$test;
Run Code Online (Sandbox Code Playgroud)

图像名称与一些显示输出的数据一起插入数据库。

/tmp/php59iuBb, /tmp/phpdRewVH, PicturesI.jpg, Screenshot.png
Run Code Online (Sandbox Code Playgroud)

我想/tmp/php59iuBb, /tmp/phpdRewVH从输出中删除它。我该怎么做。

请指导我这样做。

Art*_*nix 6

我会这样做

$images =[
    '/tmp/php59iuBb', '/tmp/phpdRewVH', 'PicturesI.jpg', 'Screenshot.png'
];

$images = preg_grep('~^(?!/tmp/)~', $images);

print_r($images);
Run Code Online (Sandbox Code Playgroud)

输出量

Array
(
    [2] => PicturesI.jpg
    [3] => Screenshot.png
)
Run Code Online (Sandbox Code Playgroud)

沙盒

简单吧!

Preg grep对数组运行正则表达式,并返回匹配项。

在这种情况下

  • ~^(?!/tmp/)~ 负向后看-确保匹配不以 /tmp/

剩下的就是我们想要的。

另一种选择是

 $images = array_filter($images,function($image){
               return substr($image, 0, 5) != '/tmp/';
           });
Run Code Online (Sandbox Code Playgroud)

如果您没有感受到Regex的爱。

沙盒

PS我喜欢preg_grep,它经常被忽略,以便于理解,但冗长。Preg Filter是其中的另一个,您可以使用它们为整个数组添加前缀或后缀。例如,我用它在文件名等的路径之前添加了前缀。例如,这很简单:

$images =[
    '/tmp/php59iuBb', '/tmp/phpdRewVH', 'PicturesI.jpg', 'Screenshot.png'
];

print_r(preg_filter('~^(?!/tmp/)~', '/home/images/', $images));
//or you can add a whole image tag, if you want, with a capture group (.+) and backrefrence \1
print_r(preg_filter('~^(?!/tmp/)(.+)~', '<img src="/home/images/\1" />', $images));
Run Code Online (Sandbox Code Playgroud)

输出量

Array
(
    [2] => /home/images/PicturesI.jpg
    [3] => /home/images/Screenshot.png
)

Array
(
    [2] => <img src="/home/images/PicturesI.jpg" />
    [3] => <img src="/home/images/Screenshot.png" />
)
Run Code Online (Sandbox Code Playgroud)

沙盒

我认为您可能会发现“技巧”很有用,因为您可以同时删除坏的东西并添加一条通往好东西的路径。他们值得一试。

http://php.net/manual/zh/function.preg-grep.php

http://php.net/manual/zh/function.preg-filter.php

我觉得我应该提到匹配文件扩展名的情况,这也许也很有用,但是我将把它再留一天。

干杯!