dqrdlqpo775594 2017-01-10 19:09
浏览 124
已采纳

如何替换包括html标签的整个字符串?

i am getting the following HTML from a textbox in laravel:

<p>Just a test</p>
<p>&nbsp;</p>
<p>Just a test</p>
<p>&nbsp;</p>
<p>Just a test</p>

Basically what i want to do is just remove all the &nbsp; and also all the <p>&nbsp;</p> , i am aware that using regex's to filter HTML is a bad idea , but in my case the scenario is limited to just there 2 options i mentioned above.

So i have the below PHP code:

$replaceNbsp = array('&nbsp' , '&nbsp;' , '<p>&nbsp;</p>' );
$blog_content = str_replace($replaceNbsp , ' ' , $request->blog_content);
return $blog_content;

But now intsead of removing the <p>&nbsp;</p> completely , i get the below output.

<p>Just a test</p>
<p> ;</p>
<p>Just a test</p>
<p> ;</p>
<p>Just a test</p>

How do i replace the HTML in the description too ??

  • 写回答

3条回答 默认 最新

  • douxitao8170 2017-01-10 19:18
    关注

    In this case, there's nothing wrong with regular expressions:

    $blog_content = preg_replace( '/<p>(&nbsp;)?<\/p>/g', '', $request->blog_content );
    

    To stick with your original strategy, you need to reverse the order in the array to be order from most specific to least specific:

    $replaceNbsp = array( '<p>&nbsp;</p>', '&nbsp;' , '&nbsp' );
    $blog_content = str_replace($replaceNbsp , ' ' , $request->blog_content);
    

    This way, it replaces the versions wrapped in <p> tag first, THEN the &nbsp; without <p> tags, etc.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?