我在服务器上插入多个图像,并在 SQL 数据库中存储名称,用 (,) 分隔。
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;
图像名称连同它显示输出的一些数据一起插入到数据库中。
/tmp/php59iuBb, /tmp/phpdRewVH, PicturesI.jpg, Screenshot.png
我想从输出中删除此 /tmp/php59iuBb,/tmp/phpdRewVH
我该怎么做。
请指导我这样做。
最佳答案
我会这样做
$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/';
});
如果您不喜欢 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));
输出
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
我觉得我应该提到匹配文件扩展名也是如此,这可能也很有用,但我会改天再说。
干杯!
关于php - 如何从数组输出中删除垃圾数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55136381/