douyanyan1123 2014-02-24 20:40
浏览 10
已采纳

too long

I'm outputting a huge string which is created by a WYSIWYG editor. The following is an example of an output that the editor makes. I'm trying to prevent all the spaces created by the &nbsp's from the beginning and end (inside each tag), so that the tags tightly wrap the content. Rtrim and Ltrim don't work because they trim the whole string, not the tags inside it.

Here is an example of a string.

<div>&nbsp; &nbsp; &nbsp; Small&nbsp;amount of text, should be&nbsp;alot.</div>
<div>Small&nbsp;amount of text, should be&nbsp;alot. &nbsp; &nbsp; &nbsp; </div>

This will output something along the lines of the following (the div has been left in to show the extent of the spaces, but would be hidden on output.)

<div>   Small amount of text, should be alot.</div>
<div>Small amount of text, should be alot.   </div>

I would prefer this out output..

<div>Small amount of text, should be alot.</div>
<div>Small amount of text, should be alot.</div>

How can this be achieved?

  • 写回答

3条回答 默认 最新

  • duanhuang4841 2014-02-24 20:51
    关注

    Replace repetitions of spaces and/or &nbsp; with a single &nbsp:

    preg_replace('/(?:&nbsp;| ){2,}/', '&nbsp;', $string);
    

    If you want to convert all &nbsp; to spaces, and then collapse the spaces then:

    preg_replace('/ {2,}/', ' ', str_replace('&nbsp;', ' ', $string));
    

    Note that this is not going to remove single spaces from after the opening tag, or before the closing tag. For something like that you're getting into some pretty nasty territory with regular expressions and you'll want to parse the document using DOM or XML instead.

    However, leading and trailing whitespace is generally insignificant in HTML, so this should get you where you're going.

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

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP