Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove <p> tag and its content from HTML using php

Tags:

html

php

Below is the text I need to remove <p> tags from

<p> Addiction, stress and subjective wellbeing</p> 
<p> The need and significance of traditional shop lot pavements in the context of town conservation in Malaysia</p> 
<p> The role of wage and benefit in engaging employee commitment</p>

I tried this

$title= preg_replace('#<p>(.*?)</p>#', '', $title['result']);**

But still am Getting <p> tags, any ideas?

like image 444
spsaravananct Avatar asked Aug 26 '12 14:08

spsaravananct


People also ask

How to remove all HTML tags from PHP string with content?

Use PHP's strip_tags () function. Remove all HTML tags from PHP string with content! Let say you have string contains anchor tag and you want to remove this tag with content then this method will helpful.

Does PHP strip_tag work with partial HTML tags?

However, if your user puts only the opening HTML Script Element then PHP strip_tag will not remove it. Then your web page will very likely display utterly wrong. Tested with PHP version 5.6.19. This little regex fixed those partial HTML tags that can cause problems that strip_tag will miss.

How to catch and remove <p> tag and all its content?

You must use this regular expression to catch <p> tag and all of its content: Working example to catch and remove <p> tag and all of its content: $title = "<div>Text to keep<p class='classExample'>Text to remove</p></div>"; $result = preg_replace ('/<p\b [^>]*> (.*?)<\/p>/i', '', $title); echo $result;

How do I remove tags from a string in Python?

Replace the terms " tag " with the respective opening and closing tags you wish to remove and $str with your string. These tags in the string will get replaced with whatever you set as the second argument, in this case, removed since we have used empty quotes "".


1 Answers

You must use this regular expression to catch <p> tag and all of its content:

'/<p\b[^>]*>(.*?)<\/p>/i'

Working example to catch and remove <p> tag and all of its content:

$title = "<div>Text to keep<p class='classExample'>Text to remove</p></div>";
$result = preg_replace('/<p\b[^>]*>(.*?)<\/p>/i', '', $title);
echo $result;

Please see live demo on Codepad

If you want to use regular expressions to parse HTML - then you will not be able to do this.

Read more about your matter here: How do you parse and process HTML/XML in PHP?

like image 61
Ilia Avatar answered Sep 19 '22 18:09

Ilia