preg_match_all,然后在使用php循环时删除重复项

preg_match_all,然后在使用php循环时删除重复项,php,for-loop,duplicates,preg-match-all,duplicate-removal,Php,For Loop,Duplicates,Preg Match All,Duplicate Removal,虽然这里有很多类似的问题和答案,我已经尽了最大的努力让它工作,但没有运气。这是我的代码: $content = "Blah...blah...[image=1], blah...blah...blah...[image=2], blah...blah...blah...[image=1], no more..."; function get_image($content) { $stripper = $content; pre

虽然这里有很多类似的问题和答案,我已经尽了最大的努力让它工作,但没有运气。这是我的代码:

$content = "Blah...blah...[image=1], 
            blah...blah...blah...[image=2],
            blah...blah...blah...[image=1], no more...";

function get_image($content) 
{ 
  $stripper = $content;   
  preg_match_all("/\[image=(.+?)\]/smi",$stripper, $search);
  $total = count($search[0]);    
    for($i=0; $i < $total; $i++) 
    {    
      $image_id = $search[1][$i];
      if($image_id > 0)
      {
        $image = 'This is an image: <img src="images/'.$image_id.'.jpg" />';
      }
      $stripper = str_replace($search[0][$i], $image, $stripper); 
    } 
  return $stripper; 
}    
$content=“诸如此类……[image=1],
等等等等等等…[图像=2],
废话…废话…废话…[图像=1],没有更多;
函数get_image($content)
{ 
$stripper=$content;
preg_match_all(“/\[image=(.+?)\]/smi”,$stripper,$search);
$total=计数($search[0]);
对于($i=0;$i<$total;$i++)
{    
$image_id=$search[1][$i];
如果($image\u id>0)
{
$image='这是一个图像:';
}
$stripper=str_replace($search[0][$i],$image,$stripper);
} 
返回$stripper;
}    
我想删除重复的“[image=1]”并返回:

Blah...blah...This is an image: <image>, 
blah...blah...blah...This is an image: <image>, 
blah...blah...blah..., no more...
诸如此类……诸如此类……这是一幅图像:,
诸如此类……诸如此类……诸如此类……这是一幅图像:,
废话…废话…废话…,不要再。。。

Blah…Blah。。。,
诸如此类……诸如此类……诸如此类……这是一幅图像:,
废话…废话…废话…这是一张图片:,不再。。。
请参阅上的手册

使用状态变量跳过以前的值,如下所示:

  $content = preg_replace_callback(
      "/\[image=(.+?)\]/smi",
      function ($m) {
          global $skip_images;
          $image = $m[1];
          if ( !isset($skip_images[$image]) ) {
              $skip_images[$image] = 1;
              return "<img src=$image.jpeg>";
          }
      },
      $content
  );
$content=preg\u replace\u回调(
“/\[image=(.+?)\]/smi”,
功能(百万美元){
全球$skip_图像;
$image=$m[1];
如果(!isset($skip_images[$image])){
$skip_images[$image]=1;
返回“”;
}
},
$content
);

显然,$skip_images代码可以写得更好;使用闭包状态变量,或者如果在其他地点或时间使用该回调,则必须清除该变量。

so。。在循环之前使用array\u unique。与使用辅助
str\u replace()
相比,使用preg\u replace\u回调更好。在数组()中使用状态变量和
跳过前面的值。@AD7six我尝试过:$total=count(array\u unique$search[0]);但不工作。@mario怎么了?你能给我举个例子吗?
  $content = preg_replace_callback(
      "/\[image=(.+?)\]/smi",
      function ($m) {
          global $skip_images;
          $image = $m[1];
          if ( !isset($skip_images[$image]) ) {
              $skip_images[$image] = 1;
              return "<img src=$image.jpeg>";
          }
      },
      $content
  );