Francois Francois -4 years ago 101
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.



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="">
<textarea name="content" cols="35" rows="12" id="content"><?
if (isset($_GET['content'])) echo $_GET['content']; ?></textarea>
<input name="parse" type="submit" id="parse" value="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);

foreach ($data as $title) {
if (substr_count($title, '[')||substr_count($title, ']')){

}else {

echo '<br />';

Thanks for your ideas.

Answer Source

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>';
echo '</pre>';

    [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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download