如何使用 php 从 HTML 中删除 <p> 标签及其内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12130966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I remove <p> tag and its content from HTML using php
提问by spsaravananct
Below is the text I need to remove <p>tags from
以下是我需要从中删除<p>标签的文本
<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?
但仍然是获取<p>标签,有什么想法吗?
采纳答案by Tarun
just to remove p tags you can do this
只是为了删除 p 标签,你可以这样做
$text=str_ireplace('<p>','',$text);
$text=str_ireplace('</p>','',$text);
回答by Ilia Rostovtsev
You must use this regular expression to catch <p>tag and all of its content:
您必须使用此正则表达式来捕获<p>标签及其所有内容:
'/<p\b[^>]*>(.*?)<\/p>/i'
Working example to catch and remove <p>tag and all of its content:
捕获和删除<p>标签及其所有内容的工作示例:
$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.
如果您想使用正则表达式来解析 HTML - 那么您将无法做到这一点。
Read more about your matter here: How do you parse and process HTML/XML in PHP?
在此处阅读有关您的问题的更多信息:您如何在 PHP 中解析和处理 HTML/XML?
回答by MaxEcho
Try:
尝试:
If you want to remove <p>tag only
如果您只想删除<p>标签
$html = "
<p> Addiction, stress and subjective wellbeing</p>
<p> The need and significance of traditional shop lot pavements town</p>
<p> The role of wage and benefit in engaging employee commitment</p>
";
echo strip_tags($html);
If you want to remove <p>tags and its content
如果要删除<p>标签及其content
$html = preg_replace('#\<p>[{\w},\s\d"]+\</p>#', "", $html);
回答by Porta Shqipe
echo "<div id=\"main_content\">" . strip_tags($row[main_content]) . "</div>";
回答by moonwave99
If you just need to strip allthe markup, go with strip_tags().
如果您只需要删除所有标记,请使用strip_tags()。
回答by Ramesh
$text = '<p>Test paragraph.</p> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "\n";
// Allow p and a tag
echo strip_tags($text, '<p><a>');
回答by CGN
This code removes one p-tag:
此代码删除了一个 p 标签:
function parse($html) {
$dom = new DOMDocument();
@$dom->loadHTML($html);
$ps = $dom->getElementsByTagName('p');
//die('<pre>'.print_r($ps,1).'</pre>');
if ($ps->length === 1){
$p = $ps->item(0);
return $p->nodeValue;
} else {
return '';
}
}

