How do I escape this?

Discussion in 'PHP' started by Imozeb, Jun 29, 2010.

  1. #1
    I am getting a string from a database which contains ' and "
    I am outputing the string to html like this.


    $htmldata =<<<htmldata
    
    <b onmouseover="my_func('$data')">$data</b>
    
    htmldata;
    echo $htmldata;
    PHP:
    Since $data has ' and " I am getting this error in my html validator: "Unterminated String Constant"

    How do I fix this? I've tried escaping $data many different ways, but none of them are working.
     
    Imozeb, Jun 29, 2010 IP
  2. themullet

    themullet Member

    Messages:
    110
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    26
    #2
    below should do the trick

    str_replace('"','\"', str_replace ("'","\\'",$data))
    PHP:
    needs slashes in front of both ' and " in data variable.

    Failing that - mysql_escape_string($data);
     
    themullet, Jun 29, 2010 IP
  3. AnubisTheJackle

    AnubisTheJackle Peon

    Messages:
    7
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    The only problem with mysql_escape_string that I can see is that for you to use it it requires you to have an open database connection, which is fine if you do, but will lead to new and exciting errors if you don't.
     
    AnubisTheJackle, Jun 29, 2010 IP
  4. krsix

    krsix Peon

    Messages:
    435
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #4
    i really don't see why you don't just assign it an id and use addEventListener('mouseover' elsewhere to bind to it
     
    krsix, Jun 29, 2010 IP