如何使用php从HTML中删除<p>标签及其内容

sps*_*nct 8 html php

以下是我需要删除<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>
Run Code Online (Sandbox Code Playgroud)

我试过这个

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

但仍然在获取<p>标签,任何想法?

Ili*_*sev 19

您必须使用此正则表达式来捕获<p>标记及其所有内容:

'/<p\b[^>]*>(.*?)<\/p>/i'
Run Code Online (Sandbox Code Playgroud)

捕获和删除<p>标记及其所有内容的工作示例:

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

请在Codepad上查看现场演示

如果您想使用正则表达式来解析HTML - 那么您将无法执行此操作.

在此处阅读有关您的问题的更多信息:如何在PHP中解析和处理HTML/XML?


Tar*_*run 6

只是为了删除 p 标签,你可以这样做

$text=str_ireplace('<p>','',$text);
$text=str_ireplace('</p>','',$text);    
Run Code Online (Sandbox Code Playgroud)

  • @MarcoPanichi 如果我给出的答案解决了提问者的问题,那么这对您有何影响。如果使用上述解决方案无法解决您的问题,请在 stackoverflow 中提出您的问题,而不是否决我的答案。 (2认同)

Sal*_*lim 5

尝试:

如果您只想删除<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);
Run Code Online (Sandbox Code Playgroud)

如果你想删除<p>标签及其content

$html = preg_replace('#\<p>[{\w},\s\d"]+\</p>#', "", $html);
Run Code Online (Sandbox Code Playgroud)