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

前端 未结 3 518
感情败类
感情败类 2021-01-29 01:53

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

3条回答
  •  伪装坚强ぢ
    2021-01-29 02:38

    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

提交回复
热议问题