harry
harry

Reputation: 33

Duplicate remove from foreach

I want to remove duplicates image. How to use array_unique? This is what I have tried:

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

Upvotes: 1

Views: 132

Answers (3)

harry
harry

Reputation: 33

I used preg_match because in the text the pictures are from the path

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

Upvotes: 0

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

First, explode() the string around " " then call array_unique(). Eg below:

$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 )

Read more:

Upvotes: 1

VisioN
VisioN

Reputation: 145408

array_unique should be applied to an array. So split your string into chunks and use it:

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

Upvotes: 1

Related Questions