I'm trying to write a script that reads in a file with a bunch of definitions in it. The definitions are setup correctly, meaning they have apostrophes in place as needed. But I have to strip out the php control apostrophes (not the ones used for escaping text) so that only the text is displayed in the form.
The user may alter the text of one of the definitions so the script would read in the submitted form, make sure all of the apostrophes are escaped, if needed, and save it.
I've been working on this, off and on, for a month but I just can't figure out how to re-add the apostrophes. I'm hoping someone here can see a way around this.
The code below simulates the actual code, which is much larger, but the output illustrates the problem I am having. Most of the code is just simulating the actual code so it would be less to look at. The output of the code will look like as shown below. It shows the way the definitions appear in the file, how they appear to the user in the form and what is to be saved to disk, which is where I'm blocked. Can anyone offer suggestions on this?
ORIGNAL APPEARANCE
define('TEXT_A', 'Just Text');
define('TEXT_B', '\' leading slash');
define('TEXT_C', NAME);
DISPLAYED IN FORM
Just Text
\' leading slash
NAME
TO BE SAVED TO DISK
define('TEXT_A', Just Text);
define('TEXT_B', \' leading slash);
define('TEXT_C', NAME);
.
<?php
//BEGIN SIMULATION
$definesArray = array(); //simulate the file loaded in
$definesArray[] = "define('TEXT_A', 'Just Text');";
$definesArray[] = "define('TEXT_B', '\' leading slash');";
$definesArray[] = "define('TEXT_C', NAME);";
$textArray = $definesArray;
$first_apostrophe = 17; //skip the first part of each line since the length is the same in each
$defineArray = array();
foreach ($textArray as $line) {
$defineArray[] = substr($line, 0, $first_apostrophe);
}
echo 'ORIGNAL FORMAT<br>';
foreach ($textArray as $line) { echo $line . '<br>'; }
for ($i = 0; $i < count($textArray); ++$i) {
$pos1 = '';
for ($x = $first_apostrophe; $x < strlen($textArray[$i]); ++$x) {
if (empty($pos1) && $textArray[$i][$x] == "'") {
$pos1 = $x;
$x++;
continue;
} else if ($textArray[$i][$x] == "\\'") {
$x++;
continue;
} else if (! empty($pos1) && $textArray[$i][$x] == "'") {
if ($pos1 == $x || $textArray[$i][$x-1] == "\\") {
$x++;
continue;
}
$pos2 = $x;
$textArray[$i] = substr($textArray[$i], $pos1 + 1, $pos2 - $pos1 -1);
if (($pos = strpos($textArray[$i], ')')) !== FALSE) {
$textArray[$i] = substr($textArray[$i], 0 , $pos);
}
}
}
if (! is_numeric($pos1)) {
$textArray[$i] = substr($textArray[$i], 17);
if (($pos = strpos($textArray[$i], ')')) !== FALSE) {
$textArray[$i] = substr($textArray[$i], 0, $pos);
}
}
}
//ABOVE CODE IS JUST TO SIMULATE ACTUAL CODE
echo '<br>DISPLAYED IN FORM<br>';
foreach ($textArray as $line) { echo $line . '<br>'; }
echo '<br>TO BE SAVED TO DISK<br>';
for ($i = 0; $i < count($defineArray); ++$i) {
echo sprintf("%s %s);", $defineArray[$i], $textArray[$i]) .'<br>';
}