string manipulation problem

Discussion in 'PHP' started by bonecone, Dec 28, 2009.

  1. #1
    I've created a form page which I submit to itself for validation. I've defined my select list as a constant:

    
    define("SELECT_LIST", "<select name=\"select_list\"><option value=\"option1\">option1</option><option value=\"option2\">option2</option></select>");
    
    Code (markup):
    This way I can get my form to remember which option was selected when the page reloads after submission. When the form page loads I use this code

    
    $select_list = (isset($_POST[select_list])) ? str_replace("value=\"$_POST[select_list]\"", "value=\"$_POST[select_list]\" SELECTED", SELECT_LIST) : SELECT_LIST;
    
    echo $select_list;
    
    Code (markup):
    However, some of the option values contain apostrophes and the above code doesn't work when I select those values. I can't seem to come up with any combination of escape characters that will make this code work.
     
    bonecone, Dec 28, 2009 IP
  2. s_ruben

    s_ruben Active Member

    Messages:
    735
    Likes Received:
    26
    Best Answers:
    1
    Trophy Points:
    78
    #2
    Why you don't want do like this??

    
    <select name="select_list">
        <option value="option1"<?php if(isset($_POST["select_list"]) && $_POST["select_list"]=="option1"){ echo(' selected="selected"'); } ?>>option1</option>
        <option value="option2"<?php if(isset($_POST["select_list"]) && $_POST["select_list"]=="option2"){ echo(' selected="selected"'); } ?>>option2</option>
    </select>
    
    Code (markup):
     
    s_ruben, Dec 28, 2009 IP
  3. bonecone

    bonecone Peon

    Messages:
    54
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I'm using the same listbox in several different forms so I want to define it in a single PHP file and simply include that file in my form pages. Plus it involves a lot less code.
     
    bonecone, Dec 28, 2009 IP
  4. bonecone

    bonecone Peon

    Messages:
    54
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Got it working afterwords. Just had to use stripslashes on the POST variable.
     
    bonecone, Dec 28, 2009 IP