delphi - 如何转义Delphi生成的PHP引号字符串?

标签 delphi escaping

我的代码中充斥着这样的东西

    Write  (thePhpFile, '    echo "<option value=\"' +
                                    theControl.Name +
                                    '_selection\">" . $' +
                                     theControl.Name +
                                     '_values[$_POST["' +
                                      theControl.Name +
                                      '_selection"]];');

生成以下 PHP 代码

 echo "<option value=\"ComboBox1_selection\">" . 
                      $ComboBox1_values[$_POST["ComboBox1_selection"]];?>

当然有更好的方法来处理这个问题吗?也许是一个 Delphi 函数,我可以传递所需的 PHP 字符串并在必要时将其加双引号?还是我在欺骗自己?

基本算法似乎是

// assume all PHP strings are double quoted, even when it's inefficient
find the first double quote, if any
find the last double quote, if any  
for every double quote in between
   change it to \""

这听起来对吗?也许我应该自己编码?

嗯,没那么容易......在上面的代码片段中,我们不想逃避 $_POST["ComboBox1_selection"] - 最好手动编写顶部显示的困惑代码?

有什么想法吗?我现在去谷歌搜索“从delphi生成php” - 这可能是我几周前就应该做的:-/

最佳答案

您不仅仅是生成 PHP。您生成的 PHP 又生成 HTML。您的程序需要了解两种语言的字符串编码规则。为此编写两个单独的函数可能会更容易:

function QuoteStringForPHP(s: string): string;
function QuoteHTMLAttributeValue(s: string): string;

根据您的示例,您将像这样使用它们:

ControlName := theControl.Name;
ValueName := ControlName + '_values';
SelectionName := ControlName + '_selection';
Write(thePhpFile, '    echo ' +
  QuoteStringForPHP(
    '<option value=' +
      QuoteHTMLAttributeValue(SelectionName) +
    '>'
  ) +
  '.' +
  '$' + ValueName + '[$_POST[' +
    QuoteStringForPHP(SelectionName) +
  ']];'
);

编写它们很简单:

// Input: Any sequence of characters
// Output: A single-quoted PHP string literal
function QuoteStringForPHP(s: string): string;
begin
  // Commented apostrophes are only to fix Stack Overflow's code highlighting
  s := StringReplace(s, '\' {'}, '\\', [rfReplaceAll]);
  s := StringReplace(s, '''', '\''' {'}, [rfReplaceAll]);
  Result := '''' + s + '''';
end;

// Input: Any sequence of valid HTML text characters
// Precondition: s has not already had any HTML encoding applied to
//               it; i.e., no character references
// Output: A single-quoted HTML attribute value
function QuoteHTMLAttributeValue(s: string): string;
begin
  s := StringReplace(s, '&', '&amp;', [rfReplaceAll]);
  s := StringReplace(s, '''', '&apos;', [rfReplaceAll]);
  Result := '''' + s + '''';
end;

我选择使用撇号而不是引号,因为这使得 PHP 转义更容易。如果您对 PHP 字符串使用引号,那么您需要担心变量插值。有了撇号,这个问题就消失了。

通过让 QuoteStringForPHP 负责引用转义,可以使转义变得容易。不再需要猜测哪些字符需要转义,因为它们都需要转义。不需要转义的只有在转义工作完成后才添加。

关于delphi - 如何转义Delphi生成的PHP引号字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3243285/

相关文章:

delphi - DScintilla,代码折叠对我不起作用

JavaScript 从 JSP 变量中删除斜杠

hibernate - Grails/GORM/Hibernate 应用程序不是 SQL 转义输入数据

unicode - 应在输出中过滤的 Unicode 字符列表?

支持UTF-8或Unicode的Delphi SMTP组件

ios - Delphi/Firemonkey 在运行时更改 iOS 屏幕旋转

delphi - 如何中断 Delphi 中的查找对话框?

德尔福XE2 : TListView as tile view not working in Windows XP

jQuery、撇号和其他特殊字符

python - 处理字符串中的转义字符