2015-11-20 23 views
1

我有一個包含預定義塊的模板。它看起來像如下:查找並替換HTML中的一段代碼

<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> 

我的預定義塊:

-position1 
-position2 
-right 
  1. 我在尋找獲得上述從我的頁面陣列塊的方式;
  2. 用塊名稱替換塊與另一個內容的小函數;

例如:

function replace_block('position1', '<b>Replaced content</b>') { 
    ... code 

    And as output: 
    ... 
    <div class="col-lg-6"> 
    <b>Replaced content</b> 
    </div> 
    ... 
} 

謝謝!

+0

使用[PHP的DOM解析器(http://simplehtmldom.sourceforge.net/)。 –

+0

看看這個:http://stackoverflow.com/questions/4824503/php-domdocument-need-to-change-replace-an-existing-html-tag-wa-new-one –

+0

可能重複的[How你在PHP中解析和處理HTML/XML?](http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) – chris85

回答

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; 
    } 
+2

regexes?在HTML?你必須在這裏新... http://stackoverflow.com/a/1732454/118068 –

+0

如何獲得可用塊數組? – user889349