从ul - PHP中显示2个随机的li

时间:2012-08-02 08:35:09

标签: php wordpress random

希望有人能提供帮助。

我正在构建一个wordpress网站,作为设计的一部分,我有一些我想要展示的“功能面板”。

列表中总共有4个li - 但我只想在每个页面上显示2个随机的。

我可以通过CSS显示/隐藏基于页面类的每个li来实现它 - 但是我想知道是否有更优雅的方式通过PHP做同样的事情?

我的HTML在这里......我不知道从哪里开始使用PHP,似乎我在Google上搜索错误的关键字...

    <ul id="featurePanels">
  <li id="newBoatsPanel">
    <h3><a href="#">New Boats<br />
      <span>Text</span></a></h3>
  </li>
  <li id="brokeragePanel">
    <h3><a href="#">Brokerage<br />
      <span>Text</span></a></h3>
  </li>
  <li id="newsPanel">
    <h3><a href="#">News<br />
      <span>Text</span></a></h3>
  </li>
  <li id="partsPanel">
    <h3><a href="#">Parts<br />
      <span>Need text here</span></a></h3>
  </li>
</ul>

任何指针都会非常感激。

谢谢。

2 个答案:

答案 0 :(得分:0)

你可以使用 preg_match_all('/\<li.*?\>.*?\</li\>/i',$html_string,$li_list)

  • 在$ li_list中你会有一个li的数组,现在你可以随机播放,随机,拼接,切片等等...

    最后使用implode来获取HTML。

  • 答案 1 :(得分:0)

    <?php
    
    $listItems = array(
     '<li id="newBoatsPanel">your text here</li>',
     '<li id="brokeragePanel">more text here</li>',
     '<li id="newsPanel">text text text</li>',
     '<li id="partsPanel">Need text here</li>'
    );
    
    shuffle($listItems); // shuffles (randomizes the order of the elements)
    
    // print the list
    echo '<ul id="featurePanels">' . $listItems[0] . $listItems[1] . '</ul>';
    
    ?>