I've got a HTML/PHP code that I pass through a Ruby function. I want it to render a minified PHP rather than just as is. I recon that the shell command php -w would be perfect to do so.
module Haml
module Filters
module PHP
include Base
##
# @param text, string (Haml/PHP code)
#
def render(text)
`php -w <<< "<?php #{text} ?>"`
end
end
end
end
The above code breaks because the HTML/PHP string text contains special characters. What is best way of escaping them?
After posting this question and thanks to comments I did more trial and error.
I established it is caused by only four special characters: " \ $ (backtick) (double quote, backward slash, dollar sign, backtick)
I created a simple solution that works (below).
Shellwords.escapewill suffice?gsub. Letstr = 'a\b"c$e'. One is to use a block:str.gsub(/[\\"\$]/) { |s| case s; when "\\" then "\\\\\\"; when '"' then "\\\""; else "\\$"; end } #=> "a\\\\\\b\\\"c\\$e". Another is to employ a hash:h = { '\\'=>'\\\\\\', '"'=>'\\"', "$"=>'\\$' } #=> {"\\"=>"\\\\\\", "\""=>"\\\"", "$"=>"\\$"}, thenstr.gsub(/[\\"\$]/, h) #=> "a\\\\\\b\\\"c\\$e".