My code is littered with things like this
Write (thePhpFile, ' echo "<option value=\"' +
theControl.Name +
'_selection\">" . $' +
theControl.Name +
'_values[$_POST["' +
theControl.Name +
'_selection"]];');
which genrates the following PHP code
echo "<option value=\"ComboBox1_selection\">" .
$ComboBox1_values[$_POST["ComboBox1_selection"]];?>
Surely there’s a better way to handle this? Maybe a Delphi function which I can pass the desired PHP string and have it double up quotes where necessary? Or am I deluding myself?
The basic algorithm would seem to be
// 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 \""
Does that sound right? Maybe I should code it myself?
Hmmm, not so easy … in the snippet above, we wouldn’t want to escape $_POST["ComboBox1_selection"] – better just to hand code the mess shown at the top?
Any ideas? I’m off now to google “generating php from delphi” – which is probably what I should have done weeks ago :-/
You’re not just generating PHP. You’re generating PHP that in turn generates HTML. Your program will need to be aware of both languages’ string-encoding rules. It will probably be easier to write two separate functions for that:
Given your example, you’d use them like this:
Writing them is straightforward:
I chose to use apostrophes rather than quotation marks since that makes PHP escaping easier. If you use quotation marks for your PHP strings, then you need to worry about variable interpolation. With apostrophes, that problem goes away.
By making
QuoteStringForPHPresponsible for quoting and escaping, you make escaping easy. There’s no more guesswork about which characters need escaping because they all do. The ones that don’t need escaping are only added after the escaping work is complete.