从文件加载菜单

时间:2014-01-03 03:40:22

标签: php regex

我尝试过滤我的menu.info文件并通过php显示所有项目。

我的代码:

// Load menu.info
        $menu_info = file_get_contents("menu.info");

        // Find Menu Items

      $re1='(<item link=")((.*))(">)((.*))(<\\/item>)'; # Tag 1

      if ($c=preg_match_all ("/".$re1."/is", $menu_info, $matches))
      {
          /*$word3=$matches[2][0]; // Link
          $word4=$matches[4][0]; // Name*/

          print_r($matches[2]);
      }

我的menu.info

<menu>
    <item link="dashboard.htm">Dashboard-Test</item>
    <item link="dashboard2.htm">Dashboard-Test2</item>
    <item link="dashboard3.htm">Dashboard-Test3</item>
    <item link="dashboard4.htm">Dashboard-Test4</item>
</menu>

print_r($matches[2);的输出:

            Array
(
    [0] => dashboard.htm">Dashboard-Test</item>
    <item link="dashboard2.htm">Dashboard-Test2</item>
    <item link="dashboard3.htm">Dashboard-Test3</item>
    <item link="dashboard4.htm
)

所以我猜preg_match_all看不到有4而不只是1。 我真的不太了解正则表达式,所以我想这可能是模式。​​

我只想要一个这样的数组:

array(
 [0] => "Dashboard-Test",
 [1] => "Dashboard-Test2",
 [2] => "Dashboard-Test3",
 [3] => "Dashboard-Test4"
)
array(
 [0] => "dashboard.htm",
 [1] => "dashboard2.htm",
 [2] => "dashboard3.htm",
 [3] => "dashboard4.htm"
)

所以我可以使用这个信息来填充我的菜单

2 个答案:

答案 0 :(得分:1)

演示: https://eval.in/85150

$menu_info = '<menu>
    <item link="dashboard.htm">Dashboard-Test</item>
    <item link="dashboard2.htm">Dashboard-Test2</item>
    <item link="dashboard3.htm">Dashboard-Test3</item>
    <item link="dashboard4.htm">Dashboard-Test4</item>
</menu>';

 $re1='/(<item link=")((.*))(">)((.*))(<\/item>)/'; 

      if ($c=preg_match_all ($re1, $menu_info, $matches))
      {
          /*$word3=$matches[2][0]; // Link
          $word4=$matches[4][0]; // Name*/

          print_r($matches[5]);
          print_r($matches[2]);
       }

<强>输出:

Array
(
    [0] => Dashboard-Test
    [1] => Dashboard-Test2
    [2] => Dashboard-Test3
    [3] => Dashboard-Test4
)
Array
(
    [0] => dashboard.htm
    [1] => dashboard2.htm
    [2] => dashboard3.htm
    [3] => dashboard4.htm
)

答案 1 :(得分:0)

不要使用正则表达式来解析它,而是使用xml解析器。

$menu_info = simplexml_load_file("menu.info");