php foreach检查名称是否包含多次相同的字符串

时间:2014-03-21 01:35:52

标签: php

我的图片文件夹的文件格式如下

    <img src='images/AAA_1.jpg'>
    <img src='images/AAA_2.jpg'>
    <img src='images/AAA_3.jpg'>
    <img src='images/BBB_1.jpg'>
    <img src='images/BBB_2.jpg'>
    <img src='images/BBB_3.jpg'>
    <img src='images/CCC_1.jpg'>
    <img src='images/DDD_1.jpg'>
    <img src='images/EEE_1.jpg'>
    <img src='images/EEE_2.jpg'>
......

我的功能是

foreach ($those as $image) {
  if(strpos($image, $name) === 0){
          echo "<div class='box'><img src='imgs/$image'/></div>";
   }
}

$those是一个数组

  Array  ( [0] => AAA_1.jpg [1] => AAA_2.jpg [2] => AAA_3.jpg [3] => BBB_1.jpg [4] => BBB_2.jpg [5] => BBB_3.jpg [6] => CCC_1.jpg ........

我们如何测试相同格式的文件名是否还有一个?    如文件名启动AAA有3,BBB有3,C有1,D有1,EEE有2,

我想实现的是

if ( check if the file name contains same string more than once ) {
      echo "<div class='box'><img src='imgs/$image'/></div>";
   }else{
      echo "<div class='container'><img src='imgs/$image'/></div>";
   }

2 个答案:

答案 0 :(得分:1)

您可以修改my answer from here来执行此操作。这不是最有魅力的解决方案,但可以解决问题。

循环数组一次,计算指定字符串的出现次数,然后再循环输出结果:

function filter($name){
    global $carousel;
    // create array to store match counts
    $matches = array();
    foreach($carousel as $image) {
        if(!array_key_exists($name, $matches))
            $matches[$name] = 0; // initialize array keys

        if(strpos($image, $name) === 0)
            $matches[$name]++; // add to the count
    }
    // got the counts, do the outputs
    foreach($carousel as $image) {
        $class_name = 'container'; // default (only one match)
        if($matches[$name] > 1) // get number of matches from previous loop
            $class_name = 'box';
        $html = "<div class='%s'><img src='imgs/%s'/></div>" . PHP_EOL;
        echo sprintf($html, $class_name, $image); // output formatted string
    }
}

注意:使用stripos()进行不区分大小写的字符串比较

答案 1 :(得分:1)

// Assocative array containting quantities
// of duplicated images Array( [AAA] => 3, [BBB] => 3, [CCC] => 1, [DDD] => 1, [EEE] => 2)
$duplicates = Array();

// Prepare $duplicates
foreach ($those as $image) {
   // $base is string `AAA`, `BBB`
   list($base) = explode("_", $image, 2);
   $duplicates[$base] = isset($duplicates[$base]) ? ($duplicates[$base]+1) : 1;
}

// Now go thru your loop
foreach ($those as $image) {
   list($base) = explode("_", $image, 2);
   if ($duplicates[$base] > 1) {
       echo "<div class='box'><img src='imgs/$image'/></div>";
   }else{
       echo "<div class='container'><img src='imgs/$image'/></div>";
   }
}
相关问题