在HTML中查找并替换一段代码

时间:2015-11-20 18:54:54

标签: php replace preg-replace

我有一个带有预定义块的模板。它看起来如下:

class LeftPanel extends JPanel
{
    JButton exeButton;

    LeftPanel()
    {
        setLayout(null);
        setBounds(2, 42, 146, 252);

        button();
    }

    void button() 
    {       
        exebutton = new JButton("Execute");
        exebutton.setMnemonic(KeyEvent.VK_ENTER); // Shortcut: Alt + Enter
        exebutton.setBounds(4, 18, 138, 47);
        add(exebutton);
    }

    public JButton getDefaultBtn()
    {
        return exebutton;
    }
}

我的预定义块:

<body>
  <div class="row">
    <div class="col-lg-6">
      <include name="position1" type="module">
    </div>
    <div class="col-lg-6">
      <include name="position2" type="module">
    </div>
  </div>
  <div class="row">
    <div class="col-lg-10">
      <include type="content">
    </div>
    <div class="col-lg-2">
      <include name="right" type="module">
    </div>
  </div> 
</body>
  1. 我正在寻找从我的页面获取上面数据块的方法;
  2. 用块名称替换块与其他内容的小函数;
  3. 例如:

    -position1
    -position2
    -right
    

    谢谢!

1 个答案:

答案 0 :(得分:1)

试试这个:

    <?php

    echo replaceBlock('position1', 'this is a replacement string', $html);

    function replaceBlock($name,$replacement,$html) {
            $pattern = '/(<include name="' . $name . '".*?>)/';
            if (preg_match($pattern, $html, $matches)) {
                    $html = str_replace($matches[1],$replacement,$html);
            }
            return $html;
    }