【问题标题】:Ruby fetch image tag from content field in dbRuby 从数据库中的内容字段中获取图像标签
【发布时间】:2023-03-05 08:07:01
【问题描述】:

在我的应用程序中,我有文章模型,并且有内容字段,其中存储了我所有的新闻文章 html 数据,例如图像视频等...

但现在我需要格式化 rss 提要,我必须获取所有这些 img 标签,并将它们放置到其他 xml 分支。

例如内容:

<h1>asdasd</h1>
content...
<img ... />

我现在的 rss 构建器视图是这样的:

xml.instruct! :xml, :version => "1.0"#, :encoding => "windows-1251" 
xml.rss :version => "2.0" do
xml.channel do
for article in @posts
      xml.item do
        xml.title article.title
xml.description article.intro_text
end
end
end

也许使用 gsub、正则表达式之类的东西?或者怎么做更好?请给个建议。谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby xml rss


    【解决方案1】:

    您可以使用String#scan 方法,该方法返回与提供的正则表达式模式匹配的字符串数组。你只需要想出模式来匹配你想要拉出的图像标签。

    a = "cruel world"
    a.scan(/\w+/)        #=> ["cruel", "world"]
    a.scan(/.../)        #=> ["cru", "el ", "wor"]
    a.scan(/(...)/)      #=> [["cru"], ["el "], ["wor"]]
    a.scan(/(..)(..)/)   #=> [["cr", "ue"], ["l ", "wo"]]
    

    为了匹配img标签,你可以试试我从another SO answer复制的这个模式。

    <img\s[^>]*?src\s*=\s*['\"]([^'\"]*?)['\"][^>]*?>
    

    这种模式似乎按照rubular test 工作。

    【讨论】:

    • hm,你能帮我把这个 拿来吗?
    • @brabertaser1992 一个简单的谷歌搜索会产生很多结果。我已经更新了我的答案,以包含我从另一个 SO 答案中复制的模式。
    • 不完全是我的意思,在 img 中可能是样式等,所以我需要获取整个 ,但是好的,我会尝试搜索
    猜你喜欢
    • 2015-07-12
    • 1970-01-01
    • 2015-02-08
    • 2012-06-09
    • 2014-05-24
    • 1970-01-01
    相关资源
    最近更新 更多