module ActionView::Helpers::TextHelper

def highlight(text, phrases, options = {}, &block)

# => ruby on rails
highlight('ruby on rails', 'rails', sanitize: false)

# => You searched for: rails
highlight('You searched for: rails', 'rails') { |match| link_to(search_path(q: match, match)) }

# => You searched for: rails
highlight('You searched for: rails', 'rails', highlighter: '\1')

# => You searched for: rails
highlight('You searched for: rails', ['for', 'rails'], highlighter: '\1')

# => You searched for: ruby, rails, dhh
highlight('You searched for: ruby, rails, dhh', 'actionpack')

# => You searched for: rails
highlight('You searched for: rails', /for|rails/)

# => You searched for: rails
highlight('You searched for: rails', 'rails')

for :sanitize will turn sanitizing off.
is sanitized to prevent possible XSS attacks. If the input is trustworthy, passing false
\1) or passing a block that receives each matched term. By default +text+
as a single-quoted string with \1 where the phrase is to be inserted (defaults to
a :highlighter string. The highlighter can be specialized by passing :highlighter
Highlights one or more +phrases+ everywhere in +text+ by inserting it into
def highlight(text, phrases, options = {}, &block)
  text = sanitize(text) if options.fetch(:sanitize, true)
  if text.blank? || phrases.blank?
    text || ""
  else
    match = Array(phrases).map do |p|
      Regexp === p ? p.to_s : Regexp.escape(p)
    end.join("|")
    if block_given?
      text.gsub(/(#{match})(?![^<]*?>)/i, &block)
    else
      highlighter = options.fetch(:highlighter, '<mark>\1</mark>')
      text.gsub(/(#{match})(?![^<]*?>)/i, highlighter)
    end
  end.html_safe
end