Tags
Asked 3 years ago
9 Jun 2021
Views 202
sarah

sarah posted

how to strip just <p> tags in php ?

how to strip just <p> tags in php ?
steave

steave
answered Apr 26 '23 00:00

To strip just the < p > tags from a string in PHP, you can use the strip_tags () function with the optional second parameter to allow only the < p > tag.

Here's an example:



$string_with_p_tags = "<p>This is some <strong>text</strong> with <a href='#'>HTML</a> tags.</p>";
$stripped_string = strip_tags($string_with_p_tags, '<p>');
echo $stripped_string;

Output:



This is some text with HTML tags.

In this example, the strip_tags () function is used with the second parameter set to allow only the < p > tag. As a result, all other tags are removed from the input string, but the < p > tags are retained.

Note that if the <p> tags contain attributes (such as <p class="my-class">), those attributes will also be retained in the output string. If you want to remove the attributes as well, you can use a regular expression to achieve this. Here's an example:



$string_with_p_tags_and_attributes = "<p class='my-class'>This is some <strong>text</strong> with <a href='#'>HTML</a> tags.</p>";
$stripped_string = preg_replace('/<p[^>]*>/', '', $string_with_p_tags_and_attributes);
echo $stripped_string;

Output:



This is some text with HTML tags.

In this example, the preg_replace () function is used with a regular expression that matches any <p> tag with attributes, and replaces it with an empty string. As a result, the <p> tags and their attributes are removed from the input string.
Post Answer