从foreach删除重复

时间:2018-02-15 15:36:21

标签: php foreach duplicates array-unique

我想删除重复的图片。如何使用array_unique?这就是我的尝试:

$text = 'text image.jpg flower.jpg txt image.jpg';
$pattern = '/[\w\-]+\.(jpg|png|gif|jpeg)/';
$result = preg_match_all($pattern, $text, $matches);
$matches = $matches[0];

foreach ($matches as $klucz => $image) { 
    echo $image;
}

3 个答案:

答案 0 :(得分:1)

array_unique应该应用于数组。因此,将您的字符串拆分为块并使用它:

$names = array_unique(explode(' ', $text));

答案 1 :(得分:1)

首先,explode() " "周围的字符串然后调用array_unique()。如下:

$text = 'text image.jpg flower.jpg txt image.jpg';
$arr = explode(" ", $text);
$arr = array_unique($arr);
print_r($arr); // Array ( [0] => text [1] => image.jpg [2] => flower.jpg [3] => txt )

了解更多:

答案 2 :(得分:0)

我使用了preg_match,因为在文本中图片来自路径

$text = 'text image.jpg flower.jpg txt <img src="path/image.jpg" '>;
相关问题