PHP - 如何搜索字符串的键和值?

时间:2011-10-11 04:26:30

标签: php arrays search

我正在尝试在CSS中找到一个已转换为数组的字符串。我想要做的是在数组的键或值中找到一个字符串,并显示css块。

我尝试了几个小时,但无法取得任何进展。

有什么建议吗?

使用http://pastebin.com/fstMwd3q

上的PHP css解析器生成代码

下面的示例是查找带有字符串“upload”的css块,并显示具有该字符串的每个css块。另一个例子是找到所有具有内联块的css。

Array
(

    [.qq-upload-cancel] => Array
        (
            [font-size] => 11px
        )

    [.qq-upload-failed-text] => Array
        (
            [display] => none
        )

    [.qq-upload-fail .qq-upload-failed-text] => Array
        (
            [display] => inline
        )

    [span.iconmorehelp] => Array
        (
            [display] => inline-block
            [height] => 18px
            [width] => 18px
        )

    [a.iconmoreinfo] => Array
        (
            [height] => 18px
            [width] => 18px
            [display] => inline-block
            [margin-top] => 3px
            [margin-right] => 3px
        )
)

* 这是我的代码基于下面的willium解决方案。如果有人可以使这更简单,请发布!! *

foreach($array as $key=>$item) {
    global $needle;
    $found = false;
    $result1='';
    $result2='';

    $result1=$key;
    if(strpos($key, $needle)) {
        $found=true;
    }
    foreach($item as $key=>$value) {        
        $result2.= $key . ":";
        $result2.= $value .":\n";
        if(strpos($key, $needle) || strpos($value, $needle)) {
            $found=true;
        }

    }
    if($found) echo "<pre>" . $result1 . "\n{\n" . $result2 . "\n}\n\n </pre>";
}

2 个答案:

答案 0 :(得分:2)

你可以遍历数组并使用foreach循环解析键值。

foreach($array as $item) {
    foreach($item as $key=>$value) {
        echo $key;
        echo $value;
    }
}

答案 1 :(得分:1)

实现目标的最简单方法是在cssparser类中添加另一种方法。

/**
*    Returns an arrray of rule names containing
*    the text in $cssFrag
**/ 
function findByCss($cssFrag)
{
    $result = null;
    $cssFrag = strtolower($cssFrag);
    $css = $this->css;
    foreach($css as $selector => $rule){
        if(stripos($selector, $cssFrag)){
            $result[] = $selector;
        } else {
           foreach($rule as $key => $property){
               if(stripos($key, $cssFrag) || stripos($property, $cssFrag)){
                   $result[] = $selector;
               }
           }
        }
    }
    return $result;
}

然后你可以$rules = $cssparser->findByCss('inline');

相关问题