【问题标题】:Rails: split an HTML string between words onlyRails:仅在单词之间拆分 HTML 字符串
【发布时间】:2014-09-30 02:51:11
【问题描述】:

给定这个变量:

=> str = " and then there was a gigantic <a href="link.com/bug.jpg">bug</a> on her nose!"

如何编写一个函数,而不是像这样在达到字符限制的地方中断:

=> str[0..33] = " and then there was a gigantic <a "

我有一些可以很好地与 HTML 配合使用的东西,如果打开标签,则返回结束标签:

=> some_function(str) = " and then there was a gigantic <a href="link.com/bug.jpg">bug</a>"

我什至会满足于返回更糟糕的东西,例如:

=> worse_function(str) = " and then there was a gigantic"

任何帮助都会很棒。显然它必须有一个粗略的字符限制,甚至是字数限制。

更新

到目前为止,我有这个:

def friendly_excerpt(string, length)
  excerpt = string.split[0..length].to_s
  if excerpt.include?('<') && !excerpt.include?('>')
    friendly_excerpt = excerpt.slice(0..(excerpt.index('<')))
  end
  friendly_excerpt
end

【问题讨论】:

  • 你目前得到的代码在哪里?

标签: html ruby-on-rails regex ruby-on-rails-3


【解决方案1】:

我愿意:

  1. 计算字符串中有多少个&lt;
  2. 检查所有&lt;的索引
  3. &lt;&gt;的位置移除标签

所以它会是这样的:

def remove_html_tag(str)
  result = str
  tag_count = str.count('<')

  for i in 0..tag_count do
    index_1 = result.index('<')
    index_2 = result.index('>')
    result = result[0...index_1] + result[index_2..-1] 
    # the above line remove one html <> tag, and it repeats
  end

  result
end

【讨论】:

    【解决方案2】:

    我有这个解决方案:

    def friendly_excerpt(string, length)
      excerpt = string.split[0..length].join(' ')
      if excerpt.include?('<') && !excerpt.include?('>')
        friendly_excerpt = excerpt.slice(0..(excerpt.index('<') - 1)).strip
      else
        friendly_excerpt = excerpt.strip
      end
      friendly_excerpt
    end
    

    似乎工作得很好。

    【讨论】:

    • 看起来比我做的更好更干净。感谢分享。
    【解决方案3】:

    如果您的目标是干净地截断包含 HTML 的字符串,而不是自己编写函数,我推荐 gem html_truncator。它使用 Nokogiri 解析 HTML,然后适当地处理截断。

    示例(GitHub page 上还有更多示例):

    HTML_Truncator.truncate("<p>Lorem ipsum dolor sit amet.</p>", 3)
    # => "<p>Lorem ipsum dolor…</p>"
    

    请注意,它默认采用 words 而不是 characters 中的截断长度参数,但可以选择使用字符。

    HTML_Truncator.truncate("<p>Lorem ipsum dolor sit amet.</p>", 12, :length_in_chars => true)
    # => "<p>Lorem ipsum…</p>"
    

    【讨论】:

      【解决方案4】:

      在看到 HTML 的那一刻,我转向 Nokogiri,因为我无法处理 HTML 开始和结束元素。我已经尝试过多次失败。假设您安装了 Nokogiri...

      html_string = ' and then there was a gigantic <a href="link.com/bug.jpg">bug</a> on her nose!'
      min_length = 33
      res = Nokogiri.HTML(html_string)
      nodes = res.elements.children.children.children #I wish I knew why all of these are needed.
      nodes.reduce('') { |new_string, node| 
         break new_string if new_string.length > min_length; 
         new_string + node.to_html 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-24
        • 2020-02-14
        • 1970-01-01
        • 2022-12-07
        • 2012-12-14
        • 1970-01-01
        • 2022-01-21
        • 2017-11-02
        相关资源
        最近更新 更多