在 Ruby 中执行一个 shell 脚本,将 HTML/PHP 代码作为参数传递



我有一个通过Ruby函数传递的HTML/PHP代码。我希望它呈现一个缩小的 PHP,而不仅仅是原样。我认为 shell 命令php -w这样做是完美的。

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

上面的代码中断是因为 HTML/PHP 字符串text包含特殊字符。逃避它们的最佳方法是什么?


发布此问题后,感谢评论,我做了更多的试验和错误。

我确定它仅由四个特殊字符引起:" $ (backtick)(双引号、反斜杠、美元符号、反引号(

我创建了一个有效的简单解决方案(如下(。

在命令行上传递内容不仅有风险,而且首先是错误的方法。使用像Open3这样的工具通过直接流式传输来做到这一点,这完全避免了转义的需要。

将输入输入到php -w进程的 STDIN 文件句柄:

output = ''
Open3.popen2('php', '-w') do |stdin, stdout, wait_thr|
stdin.write("<?php #{text} ?>")
stdin.close
output << stdout.read
end

你看过这个答案吗: Ruby:转义字符串中的特殊字符

听起来像是读完文件后,您需要删除字符。

file = File.open("users.txt")
file_data = file.read
clean_data = file_data.gsub(/\/, '')

然后将您的数据打印到 shell 命令(您可以再做一些转义(

下面的替换链似乎有效,但正如一些人指出的那样,一个可能更好的解决方案是使用shellescape

# a breakdown of escaped characters
text.gsub("\", "\\\")  #    backslash (the escape character) 
text.gsub(""", "\"")    #   " double quotation mark
text.gsub("$", "\$")      #   $ dollar sign
text.gsub("`", "\\`")    #   ` backtick

修订后的法典

module Haml
module Filters
module PHP
include Base
def render(text)
text=text.gsub("\", "\\\").gsub(""", "\"").gsub("$", "\$").gsub("`", "\\`")
`php -w <<< "<?php #{text} ?>"`
end
end
end
end

最新更新