2

我有一个文本区域,用户可以在其中为每个功能块创建一个带有标题的功能列表。这个想法是将 [title] 和 features 存储在两个不同的 MySQL 表中。

[户外]
BBQ
网球场
游泳池

[内部设备]
DVD播放器
等离子屏幕

这是我到目前为止所做的;它有效,但并不整洁:

<form name="form" method="get" action="">
  <p>
    <textarea name="content" cols="35" rows="12" id="content"><? 
if (isset($_GET['content'])) echo $_GET['content']; ?></textarea>
  </p>
  <p>
    <input name="parse" type="submit" id="parse" value="Parse">
  </p>
</form>
<?php

if(isset($_GET['parse']))
{
   $content = $_GET['content'];
   $content = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $content);
   $content = trim($content);

   $content1 = preg_replace('/\r\n|\r/', "\n", $content );  
    $data = explode("\n", $content1); 


    $p=0;
   foreach ($data as $title) {
   if (substr_count($title, '[')||substr_count($title, ']')){
  $p++;
   $arr[$p]=$title;

   }else {
   $g[$p][]=$title;
   }
   }

    print_r($arr); 
    echo '<br />';
    print_r($g);
}
?>

谢谢你的想法。

4

3 回答 3

1

除此之外,请确保在您的表单中使用 POST 方法。查询字符串变量很容易被篡改。

于 2010-07-14T07:07:28.747 回答
0

在大多数情况下,代码看起来不错。

我看到的问题是您没有清理用户输入,而是直接显示它:

if (isset($_GET['content'])) echo $_GET['content']; 

至少,使用 strip_tags():

if (isset($_GET['content'])) echo strip_tags($_GET['content']));

此外,您可能应该使用 POST 而不是 GET。

编辑:

我注意到的另一件事是大括号的使用不一致。要么使用 K&R 风格:

if (some_condition) {
    code
}

或者将它们放在单独的一行(我的首选方法):

if (some_condition)
{
    code
}

(有谁知道这种风格有没有名字?)

缩进也是一样。保持一致。这只是一个样式问题,但它会影响代码的易读性。

于 2010-07-14T07:19:42.573 回答
0

这对你来说足够整洁吗?

$result = array();
$content = array_filter(array_map('trim', explode('[', $_GET['content'])), 'strlen');

foreach ($content as $value)
{
    $value = array_map('trim', explode("\n", $value));
    $result[rtrim(array_shift($value), ']')] = $value;
}

和输出:

echo '<pre>';
print_r($result);
echo '</pre>';

Array
(
    [Outdoor] => Array
        (
            [0] => BBQ
            [1] => Tennis court
            [2] => Swimming pool
        )

    [Internal Equipment] => Array
        (
            [0] => DVD Player
            [1] => Plasma screen
        )

)

我想你知道如何处理$result数组吗?就像是:

foreach ($result as $title => $features)
{
    // INSERT INTO foo (title) VALUES ($title);

    foreach ($features as $feature)
    {
        // or INSERT INTO bar (title, features) VALUES ($title, $feature);
    }
}
于 2010-07-14T07:43:56.340 回答