开发者

Is there any way to get only unique matches with preg_match_all?

Hello I want to get all the unique matches of the following. How can I do it?

preg_match_all('#http://[\S]+(?:jpe?g|png|gif)#is', $content, $filtered);

$filtered = array_unique($filtered[0]);
foreach($filtered as $value){
${'varpics' . $i} .= '<img width="200px" height="200px" src="'.$v开发者_开发问答alue.'"><br>'; }

I still get double matches.


No. Just pass the results through array_unique.

Unless you wanted to get real fancy with preg_replace_callback and push the matches into a set.


<?php
$content = <<<HTML
<img src="http://www.mysite.com/image1.jpg" />
<img src="http://www.mysite.com/image2.gif" />
<img src="http://www.mysite.com/image1.jpg" />
HTML;

preg_match_all('#http://[\S]+(?:jpe?g|png|gif)#is', $content, $matches);
$images = array_unique($matches[0]);

var_dump($images);

Works perfectly for me. Output:

array
  0 => string 'http://www.mysite.com/image1.jpg' (length=32)
  1 => string 'http://www.mysite.com/image2.gif' (length=32)

You've got a lot of other things wrong with your code though. For example, where is $i defined? And why are you trying to define variables like that? Use an array, rather than a name appended with a number... I'm not even sure if that's valid syntax.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜