删除字符串中的多个数组值

时间:2020-05-06 14:21:24

标签: php

我想删除或过滤一些不存在于其他钉中的图像值。在$ description变量中有2个图像值(images / bk5.jpg,images / bk3.jpg),在$ img变量中有4个图像值,我想要$ imgs_result(images / bk5.jpg,images / bk3.jpg)并想要删除$ img变量的另外两个图像值。

<?php 

$description ='Some paragraph... &lt;p&gt;&lt;img src=&quot;images/bk5.jpg&quot; alt=&quot;&quot; width=&quot;300&quot; height=&quot;242&quot; /&gt;&lt;img src=&quot;images/bk3.jpg&quot; alt=&quot;&quot; /&gt; Some paragraph...&lt;/p&gt;';

$img ='images/bk1.jpg images/bk3.jpg images/bk4.jpg images/bk5.jpg';

$imgpage = explode(" ",$img);

$imglength = count($imgpage);

for($x = 0; $x <= $imglength; $x++){
//This code delete the images from the database but does not remove or filter the values of variables.
   if(!stristr($description,$imgpage[$x])){

      $imgs_result = str_ireplace($imgpage[$x],"",$img);

      unlink($imgpage[$x]);

   }

}

?>

2 个答案:

答案 0 :(得分:0)

您可以使用一些函数式编程来做到这一点:

<?php

$description ='Some paragraph... &lt;p&gt;&lt;img src=&quot;images/bk5.jpg&quot; alt=&quot;&quot; width=&quot;300&quot; height=&quot;242&quot; /&gt;&lt;img src=&quot;images/bk3.jpg&quot; alt=&quot;&quot; /&gt; Some paragraph...&lt;/p&gt;';

$img ='images/bk1.jpg images/bk3.jpg images/bk4.jpg images/bk5.jpg';

$imgpage = explode(" ",$img);

$imgs_result = array_filter($imgpage, function($image) use($description) {
    return stristr($description,$image);
});

print_r($imgs_result);
  • 要查看代码工作here
  • 要了解有关函数式编程here的更多信息。
  • 可帮助您使用PHP here进行功能编程的库。

答案 1 :(得分:-1)

如果您有2个字符串,如下所示:

$description = "images/bk5.jpg, images/bk3.jpg";
$img = "images/bk5.jpg, images/bk3.jpg, images/bk1.jpg, images/bk2.jpg";

首先,您可以使用 explode()函数将字符串转换为数组。 然后,您可以使用 array_diff()函数查找这些数组之间的差异。

相关问题