开发者

Move class attribute value to php variable

We have variable $menu with HTML inside (there is no loop, it comes from a function).

On echo it gives the code like this:

<ul id="menu">
    <li id="some-id" class="many classes one"><a href="#">text</a></li>
    <li id="some-id" class="many classes second active"><a hr开发者_如何转开发ef="#">text</a></li>
    <li id="some-id" class="many classes three"><a href="#">text</a></li>
</ul>

What I want to do:

  1. get value of the class="" of each <li>.

  2. if active exists in this value, then go to 3) step.

  3. search for one, two, three, four, five inside value. If one of them exists, then throw its name to php variable.

Variable $menu should give:

$name = 'two';

What is the solution?


Use an XPath query.

see here:http://php.net/manual/en/domxpath.query.php


$html = '<ul id="menu">
    <li id="some-id" class="many classes one"><a href="#">text</a></li>
    <li id="some-id" class="many classes two active"><a href="#">text</a></li>
    <li id="some-id" class="many classes three"><a href="#">text</a></li>
</ul>';

$active = 'active';
$valid = array('one','two','three','four','five');

$x = simplexml_load_string($html);

foreach($x->xpath('//ul/li[contains(@class,'.$active.')]') as $li)
{
    if($common = array_intersect($valid, explode(' ',$li->attributes()->class)))
    {
        $menu = array_shift($common);
        break;
    }
}
echo $menu;


You should use Regular Expressions.

Or if you can catch each Li item classes in the previous functions might be easier.


I think you should wrap the solution into a function.

Regular Expressions fit for the job, but I think you can also use DOM class. Something like:

$menu = '<ul id="menu">
    <li id="some-id" class="many classes one"><a href="#">text</a></li>
    <li id="some-id" class="many classes two active"><a href="#">text</a></li>
    <li id="some-id" class="many classes three"><a href="#">text</a></li>
</ul>';
// using a constant instead a "magic number" inside below function
define(NUMBER_POSITION, 2);
function getActiveItem($menuStr) {
    $doc = new DOMDocument();
    $doc->loadXML($menuStr);
    $listItems = $doc->getElementsByTagName('li');
    foreach($listItems as $listItem) {
        // case count equals 1, expression will be true
        if (substr_count($listItem->getAttribute('class'), 'active')) {
            $classes = explode (' ',$listItem->getAttribute('class'));
            return $classes[NUMBER_POSITION];
        }
    }
}

echo getActiveItem($menu);

That's it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜