好的。你沒有指定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);
?>
您可以使用'/ [<! - ] * [az 0-9 - >] * [ - >]/igm'作爲正則表達式來獲取整個塊(從打開'<! - '到關閉' - >') – atmd 2015-02-05 16:22:54