2015-02-05 41 views
0

我想要做的是找到一塊有批註塊的HTML! -/block - >,並將其全部移動到頭後。問題在於評論始終保持不變,但塊在使用Dreamweaver中的查找和替換的頁面上有所不同。下面是一個簡單示例:用RegEx移動HTML的塊

<!--header--> 
<header>Hello</header> 
<!--/header--> 

這是塊需要移動

<h1>Hello content</h1> 
<p>lorem ipsum</p> 

這是塊的,它有一個開始註釋和結束一個,我想這可能被用作包含RegEx的所有內容。

<!--block--> 
<p>hello world</p> 
<!--/block--> 
+0

您可以使用'/ [<! - ] * [az 0-9 - >] * [ - >]/igm'作爲正則表達式來獲取整個塊(從打開'<! - '到關閉' - >') – atmd 2015-02-05 16:22:54

回答

3

好的。你沒有指定reular表達式的語言,但是這個PHP代碼做了你需要的東西,我只寫了它並測試了它。 作爲獎勵,我將最終結果寫回到源頁面。

首先,你有你的原始文件,我打電話給我source.php

<!--header--> <header>SO HERE IS THE HEADER</header> <!--/header--> 

<div>this is information that is above ID CARR, but will be below the div ID carr once php is done executing..</div> 

<div id="carr"> Phasellus laoreet dolor magna, et tempor mi dictum eu. Aenean pellentesque vulputate tortor. Vestibulum odio velit, faucibus sed dui non, laoreet facilisis sem. Curabitur a magna ligula. Cras cursus vel dui placerat posuere. Donec ullamcorper risus eu lobortis dignissim. Nullam fermentum est diam, sed lacinia sapien ornare et. </div> <div>here is more informatin on the bottom</div> 

然後你叫的index.php,你想要什麼樣的另一頁。在這個例子中,我的目標是上述。

<?php 
$page_path = 'source.php'; 
$source = file_get_contents($page_path); 
$regex = '#\<div id="carr">(.+?)\</div>#s'; 
preg_match($regex, $source, $matches); 
$match = $matches[0]; 

$a = explode("</header>", $source); 
//strip out what we found with regular expression 
$first = str_replace($match, '', $source); 
//append it to the place where you need it. 
$final = str_replace('<!--/header-->', '<!--/header-->'.$match, $first); 
echo $final; 

$fp = fopen($page_path, 'w+');//w+ erases r+ point at begining of file. 
fwrite($fp, $final); 
fclose($fp); 

?> 
+0

這真是很好的解決方案!謝謝,但不幸的是,我不能用PHP做。這就是爲什麼我問是否可以使用Dreamweaver +正則表達式。我相信你的答案在任何情況下都是非常有用的。 – devjs11 2015-02-05 16:54:18