如何转义表单数据的撇号?

时间:2014-12-24 19:05:51

标签: php escaping

我正在尝试编写一个脚本,该脚本读入包含大量定义的文件。定义设置正确,这意味着它们根据需要具有撇号。但我必须删除php控件撇号(不是用于转义文本的撇号),以便只在表单中显示文本。

用户可以更改其中一个定义的文本,以便脚本在提交的表单中读取,确保所有撇号都被转义(如果需要)并保存。

我一直在研究这个问题一个月,但是我无法弄清楚如何重新添加撇号。我希望有人能在这里找到解决方法。

下面的代码模拟的实际代码要大得多,但输出说明了我遇到的问题。大多数代码只是模拟实际的代码,所以它看起来更少。代码的输出如下所示。它显示了定义在文件中的显示方式,它们在表单中对用户的显示方式以及要保存到磁盘的内容,这是我被阻止的位置。有人可以就此提出建议吗?

ORIGNAL FOREARANCE

define('TEXT_A', 'Just Text');
define('TEXT_B', '\' leading slash');
define('TEXT_C', NAME);

以表格形式显示

Just Text
\' leading slash
NAME

要保存光盘

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>';
}

0 个答案:

没有答案
相关问题