Search code examples
phpmysqltexthtml-escape-characters

How to store escaped characters in MySQL and display them in php?


For example I want to store the String "That's all". MySQL automatically escapes the ' character. How do I echo that String from the database using php but remove the \ in front of escaped characters like \' ? I would also like to preserve other formatting like new lines and blank spaces.


Solution

  • Have you tried stripslashes(), regarding the linebreaks just use the nl2br() function.

    Example:

    $yourString = "That\'s all\n folks";
    $yourString = stripslashes(nl2br($yourString));
    echo $yourString;
    

    Note: \\ double slashes will turn to \ single slashes


    You should probably setup your own function, something like:

    $yourString = "That\'s all\n folks";
    
    function escapeString($string) {
        return stripslashes(nl2br($string));
    }
    
    echo escapeString($yourString);
    

    There are also several good examples in the nl2br() docs


    Edit 2

    The reason your are seeing these is because mysql is escaping line breaks, etc. I am guessing you are using mysql_* functions. You should probably look into mysqli or PDO.

    Here is an example:

    $yourString = "That's all
     folks";
    echo mysql_escape_string($yourString);
    

    Outputs:

    That\'s all\r\n folks