用RegEx移动HTML的块

问题描述:

我想要做的是找到一块有批注块的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

您可以使用'/ [] * [ - >]/igm'作为正则表达式来获取整个块(从打开'') – atmd 2015-02-05 16:22:54

好的。你没有指定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