如何定义正则表达式以删除两个字符之间的所有内容

时间:2015-05-27 10:26:19

标签: php html regex string replace

我对正则表达式的定义有问题。在下面的代码中,我想要删除所有<p>标记以及<p >之间的所有属性,例如style="bla bla",但我希望在这种情况下保留其他元素及其属性,如<img>。我尝试了这种模式/\<p.*?\>|\s*/,但它不适合我。有人能帮助我吗?

<p style="text-align: center;">LOREM IPSUMLOREM IPSUMLOREM IPSUMLOREM IPSUMLOREM IPSUM</p>
<p>
<img class="alignnone" src="http://localhost/themify/wp-content/uploads/2015/05/fortuna_novi-300x300.png" alt="fortuna_novi" width="112" height="112">
</p>

编辑:我想得到像这样的结果

LOREM IPSUMLOREM IPSUMLOREM IPSUMLOREM IPSUMLOREM IPSUM
<img class="alignnone" src="http://localhost/themify/wp-content/uploads/2015/05/fortuna_novi-300x300.png" alt="fortuna_novi" width="112" height="112">

2 个答案:

答案 0 :(得分:0)

请参阅EJTH的评论,我不能经常重复:不要使用正则表达式进行DOM操作!

在这种情况下,如果您只想删除所有<p></p>标记,则可以使用类似

的内容
<p[^>]*>|</p>

匹配<p,除>(零次或多次)以及结束> 文字</p>

如果在属性值中出现文字>(不应该,但谁知道),您可能想要使用稍微复杂的版本,如

<p(?:\s+\w+(="[^"]*"|'[^']*'|\w+)?)*>|</p>

答案 1 :(得分:0)

以下代码段可以帮助您:

$re = "/(\\s*<p.*?\\s*>|<\\s*\\/p\\s*>)/"; 
$str = "<p style=\"text-align: center;\">LOREM IPSUMLOREM IPSUMLOREM IPSUMLOREM IPSUMLOREM IPSUM</p>\n<p>\n<img class=\"alignnone\" src=\"http://localhost/themify/wp-content/uploads/2015/05/fortuna_novi-300x300.png\" alt=\"fortuna_novi\" width=\"112\" height=\"112\">\n</p>"; 
$subst = "$1"; 

$result = preg_replace($re, $subst, $str);

DEMO