我在服务器上插入多个图像,并通过(,)分隔在SQL数据库中存储名称。
如果($请求 - > hasFile( ‘图像’)){ $ images = []; 的foreach($图像= $请求 - > …
派对迟到了,但我个人更喜欢使用 pathinfo 在这里使用正则表达式,因为它专用于文件路径:
pathinfo
$images = ['/tmp/php59iuBb', '/tmp/phpdRewVH', 'PicturesI.jpg', 'Screenshot.png']; $images = array_filter($images, function ($image) { return pathinfo($image, PATHINFO_DIRNAME) !== '/tmp'; }); print_r($images);
的 演示: https://3v4l.org/6F6K8 强>
foreach循环是声明还存储图像的临时路径 $images
$images
在foreach中更改变量名称
$images=$request->file('images') tto $image=>$request->file('images')
我会这样走,希望它可以帮助你:
$images= []; if ($request->hasFile('images')) { foreach ($request->file('images') as $img) { $name = 'some_random_sting'; $extension = $img->getClientOriginalExtension(); $imgName = $name .'.'.$extension; $img->move(public_path().'/dpic', $imgName); $images[] = $imgName; } } $test = implode(', ', $images); $product->images = $test;
我会这样做的
$images =[ '/tmp/php59iuBb', '/tmp/phpdRewVH', 'PicturesI.jpg', 'Screenshot.png' ]; $images = preg_grep('~^(?!/tmp/)~', $images); print_r($images);
产量
Array ( [2] => PicturesI.jpg [3] => Screenshot.png )
砂箱
简单吧!
Preg grep针对数组运行正则表达式并返回匹配项。
在这种情况下
~^(?!/tmp/)~
/tmp/
这让我们想要什么。
另一种选择是
$images = array_filter($images,function($image){ return substr($image, 0, 5) != '/tmp/'; });
如果你没有感受到正则表达的爱。
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));
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" /> )
我认为你可能会发现“技巧”很有用,因为你可以删除坏的并同时添加一条通往商品的路径。他们值得一试。
http://php.net/manual/en/function.preg-grep.php
http://php.net/manual/en/function.preg-filter.php
我觉得我应该提到匹配文件扩展名也是如此,这可能也很有用,但我会留下另一天。
干杯!