Francois Francois - 28 days ago 9
PHP Question

Improve my code : Distributing the content of a textarea in two different arrays depending on markers

I have a textarea where the user can create a feature list with a title for each block of features. The idea is to store the [title] and the features in two different MySQL tables.


[Outdoor]

BBQ

Tennis court

Swimming pool

[Internal Equipment]

DVD Player

Plasma screen


Here is what I've done so far; it works but it's not neat:

<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);
}
?>


Thanks for your ideas.

Answer

Is this neat enough for you?

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

And the output:

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
        )

)

I suppose you know what to do with the $result array? Something like:

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

    foreach ($features as $feature)
    {
        // or INSERT INTO bar (title, features) VALUES ($title, $feature);
    }
}