How can I remove the <p style="text-align:center"> (or left, right. The paragraph comes from database) using PHP?

StackOverflow https://stackoverflow.com/questions/23622176

  •  21-07-2023
  •  | 
  •  

Question

I have this html code that came from my database (I used TinyMCE to save the data)

<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>

How can I remove those <p></p> tags considering that there can be other styles applied when using TinyMCE?

Was it helpful?

Solution

To remove HTML tags from a string you can use 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"

To keep certain tags, you can add an additional parameter:

$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>"

The second parameter is a string listing each tag you don't want stripped, for example:

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

For more information, review the PHP documentation linked above.

OTHER TIPS

Although you mentioned that you don't use js, I would strongly encourage you to start using it. You will find it extremely useful in plenty of cases to just interfere to client-side rather than use just server-side procedures (as php does). So, just for the record, here is my suggested jQuery solution:

<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>

Live example here: http://jsfiddle.net/Rykz9/1/

Hope you (and others) find it useful... Happy coding!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top