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 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题