0

I have a textarea in my html named add-list. I want to get the value of the textarea per line break and then save it to my database. The problem is, when it saves the input to the database, the second and succeeding entries have a whitespace before the input.

Here is my function for getting the value:

public function add(){
        $checker = false;
        $names = $this->input->post('add-list');

            if (strpos($names, "\n") == TRUE ) { //newline found
                $names = nl2br(trim($this->input->post('add-list')));
                $namesArray = explode('<br />', $names);

                foreach($namesArray as $name) {
                    $checker = false;
                    $checker = $this->checkDatabase($name); //check if name already exists in database
                    if ($checker) {
                        echo "<script type='text/javascript'>alert('A site in your list already exists. Duplicate sites are not allowed.');</script>";
                    }

                    if (!$checker) {
                        $this->data_model->addCommunity($name);
                    }
                }

                $this->index();
                redirect(base_url());
            }

            else if (strpos($names, "\n") == FALSE) {
                $checker = $this->checkDatabase($names);
                if ($checker) {
                    echo "<script type='text/javascript'>alert('" . $names . " already exists. Duplicate sites are not allowed.'); window.location.href='".base_url()."'</script>";
                }

                if (!$checker) {
                    $this->data_model->addCommunity($names);
                    $this->index();
                    redirect(base_url());
                }
            }
    }

What I get in my database is like this:

firstName
 secondName //there's a whitespace before 's'

Help me please!!!

achll
  • 153
  • 1
  • 4
  • 12

1 Answers1

1

Why do you go all the way through nl2br and then explode instead of using explode with a line break? But just use the search or a search engine, e.g. Explode PHP string by new line (long time no PHP, so I might not be quite right).

Community
  • 1
  • 1
Matthias W.
  • 1,039
  • 1
  • 11
  • 23
  • if i do this, it saves
    in the database.
    – achll May 23 '14 at 08:54
  • nl2br: "Returns string with `'
    '` or `'
    '` inserted before all newlines (`\r\n, \n\r, \n and \r`)." -- if you don't use nl2br there shouldn't be `'
    '` or `'
    '` at all. Instead try to explode for each newline (`\r\n, \n\r, \n and \r`) by yourself. You might have to "normalize" the new lines for different plattforms (as you might see in the thread referenced).
    – Matthias W. May 23 '14 at 09:01