duanjianxi8439 2013-09-23 09:37
浏览 9
已采纳

逃避<br />

I'm trying to escape <br /> and the likes in my Magento meta description.

So I've come up with this:

$characters = array("<br />", "<br>", "<br/>");
$badDesc = htmlspecialchars($this->getDescription());
$goodDesc = preg_replace($characters, ' ', $badDesc);

but the only characters thats escaped is "br /", but remaining is the "< >"

What do?

  • 写回答

4条回答 默认 最新

  • dourui7186 2013-09-23 09:45
    关注

    Perhaps this is worth a shot (note: untested)

    $desc = preg_replace('/\<br\b[^>]*>/i', ' ', $this->getDescription());
    

    The expression explained:

    • \<br is a literal match for the string <br
    • \b is a word boundary: preg_match('/foo\bbar/', 'foobar') will not match, but preg_match('/foo\bbar/', 'foo bar') will match. That is, in essence a word-boundary. The beginning and ending of a word
    • [^>]* matches all chareacters except for a literal >. The asterisk states that this character class may occur zero or more times: with <br />, for example, this char class will match / (all spaces and the forward slash. Given this: <br>, then this part will be skipped (occurs zero times)
    • > is a litteral match for the close-tag > char

    If your markup is valid (ie not malformed), this expression will remove nothing you don't want to remove. But given strings like this: <br data-string="<b>Don't include markup here</b>"/> this expression will fail: there is a property that contains markup, but that is something I, personally, find revolting. You don't include markup in an attribute of a tag, IMO.
    Another case where regex lets the guard down is when encountering malformed markup:

    <br/The closing &gt; was omitted</p>
    

    The regex will match the opening <br, then the [^>]* will match:

    /The closing &gt; was omitted</p
    

    Only to match the > of </p> as the end of the br tag. But that's just the "fault" of whoever wrote the markup...

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

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计