如何删除 <p 样式 = "text-align:center" >(或左、右。该段落来自数据库)使用PHP?



我有这个html代码来自我的数据库(我使用TinyMCE保存数据)

<p style="text-align: center;">Come on grab your friends</p>
<p style="text-align: center;">Go to very distant lands</p>
<p style="text-align: center;">Jake the Dog and Finn the Human</p>
<p style="text-align: center;">The fun never ends</p>
<p style="text-align: center;"><strong>Adventure Time!</strong></p>

考虑到使用TinyMCE时可以应用其他样式,我如何删除这些<p></p>标签?

要从字符串中删除HTML标签,可以使用strip_tags():

$str = '<p style="text-align: center;">Come and grab your friends</p>';
$str2 = strip_tags($str);
echo $str2; // "Come and grab your friends"

要保留某些标签,可以添加一个额外的参数:

$str = '<p style="text-align: center;"><strong>Adventure Time!</strong></p>';
$str2 = strip_tags($str, "<strong>"); // Preserve <strong> tags
echo $str2; // "<strong>Adventure Time!</strong>"

第二个参数是一个字符串,列出您不想剥离的每个标记,例如:

$str2 = strip_tags($str, "<p><h1><h2>"); // Preserve <p>, <h1>, and <h2> tags

有关更多信息,请查看上面链接的PHP文档

虽然你提到你不使用js,但我强烈建议你开始使用它。您会发现,在很多情况下,只干预客户端而不是只使用服务器端过程(如php)是非常有用的。因此,为了记录,以下是我建议的jQuery解决方案:

<html>
<head>
<!-- your head content here -->
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<p style="text-align: center;">Come on grab your friends</p>
<p style="text-align: center;">Go to very distant lands</p>
<p style="text-align: center;">Jake the Dog and Finn the Human</p>
<p style="text-align: center;">The fun never ends</p>
<p style="text-align: center;"><strong>Adventure Time!</strong></p>
<div id="result"></div> <!-- here I have added an extra empty div to display the result -->
<script>
$(document).ready(function() {
    $("p").each(function() {
        var value = $(this).text();
        $("#result").append(value+ "<br>");
        $(this).css("display", "none");
    });
});
</script>
</body>
</html>

这里的实例:http://jsfiddle.net/Rykz9/1/

希望你(和其他人)觉得有用…编码快乐!

最新更新