在php中搜索数组内的子字符串

时间:2011-02-11 07:32:21

标签: php arrays string substring

您好我想知道是否有一个很好的算法来搜索另一个数组中的数组内的子字符串,

我有类似的东西:

阵列(

        [0] => Array(
                    [0] => img src="1" /> 
                    [1] => img src="2" alt="" class="logo i-dd-logo" /> 
                    [2] => img src="3" alt="" /> 
                    [3] => img src="4" width="21" height="21" alt="" class="i-twitter-xs" /> 
                    [4] => img src="myTarget" width="21" height="21" alt="" class="i-rss" /> 
                    [5] => <img class="offerimage" id="product-image" src="6" title="" alt=""/> 
                    [6] => <img class="offerimage" id="product-image" src="7" title="" alt=""/> 
                    [7] => <img class="offerimage" id="product-image" src="8" title="" alt=""/> 
                    [8] => <img src="9" width="16" height="16" /> 
    )

[1] => Array(
                    [0] =>  src="1" 
                    [1] =>  src="a" alt="" class="logo i-dd-logo" 
                    [2] =>  src="b" alt="" 
    )

我想要做的是知道目标的位置,例如[0] [4]但它并不总是相同的

我现在正在做的是在另一个内部,并检查子串的strith strpos,但也许有更好的方法来做这个,任何建议?

感谢您的一切


更新的代码:

  

$ I = -1;

     

foreach($ img as $ outterKey =&gt; $ outter){

            foreach($outter as $innerKey=>$inner){

      $pos = strpos($img[$outterKey][$innerKey],"myTarget");
      if (!$pos === false) {
                  $i=$outterKey;$j=$innerKey;
                  break 2;
              }
            }
    }

2 个答案:

答案 0 :(得分:0)

嗯,也许就像:

      foreach($outsideArray as $outterKey=>$outter) {
                foreach($outter as $innerKey=>$inner){
                   if(substr_count ($inner , $needle)) {
                         echo $outterKey . " and " . $innerKey;
                    }
                }
        }
编辑:可扩展,我在你的评论中注意到你希望它可以扩展。递归怎么样?

function arraySearch($array) {
    foreach($array as $key=>$item){
        if(is_array($item)
            return arraySearch($item);
        elseif(substr_count ($item , $needle)
            return $key;
    }
}

答案 1 :(得分:0)

在这里尝试此代码,您就可以获得字符串的完整位置。 这里$ find是你的子串。 $ data是你的数组。

$find = "<img src='4' width='21' height='21' alt=' class='i-twitter-xs' />";
 foreach ($data as $out_key => $out_value) 
 {
   if(is_array($out_value))
   {
     if(in_array($find, $out_value))
     {
        $out_pos = array_search($out_value, $data);
        $inn_pos =array_search($find, $out_value);
     }
   }
 }
echo $data[$out_pos][$inn_pos];