Enclosing the string with double quotes

前端 未结 3 1976
轮回少年
轮回少年 2020-12-21 21:32

I am trying to handle text which may contains single quotes and other special char. If it is enclised with single quote, it does not proceed. So I am trying to enclose singl

相关标签:
3条回答
  • Always use contextual escaping

    You can't generically "clean" data without any context of what it's for. Do not try to build a single function to handle all the possible cases. Just don't. It's pointless. In your function, you're trying to "clean" the string by removing certain characters. You can't clean a string by removing a set of characters. That idea is flawed because you're always going to have to allow the use of some characters that are special in some syntax or the other.

    Instead, treat the string according to the context where it's going to be used. For example:

    • If you are going to use this string in an SQL query, you have to use prepared statements (or mysqli_real_escape_string()) to properly escape the data.

    • If you're going to output this value in HTML markup, you need to use htmlspecialchars() to escape the data.

    • If you're going to use it as command-line argument, you need to use escapeshellcmd() or escapeshellarg().

    Further reading:

    • Security.SE — What's the best way to sanitize user input in PHP?
    • What's the best method for sanitizing user input with PHP?
    • Does eliminating dangerous characters avoid SQL-injection?
    0 讨论(0)
  • 2020-12-21 22:13

    In this answer, I'll try to address your original question:

    What wrong with eval line?

    Nothing. The second-to-last line is the only line that contains a syntax error. You aren't escaping the single-quotes correctly. Try the following:

    $d = clean('this was readlly n\'ice \'test for@me to');
    

    It should now produce this output:

    this was readlly nice test for@me to
    

    I'm not sure if this is the expected result. If you update the question to include what exactly you're trying to achieve and why do you care which type of quotes the string was wrapped in, maybe I can help you find a solution.

    0 讨论(0)
  • 2020-12-21 22:18

    Try this one-

    <?php
    function clean($string) {
        eval("\$string = \"$string\";");
       $string = str_replace(' ', ' ', $string); // Replaces all spaces with hyphens.
       return preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $string); // Removes special chars.
    }
    
    $d =  clean("this was readlly n'ice 'test for@me to") ;
    echo $d;
    ?>
    

    The output is- this was readlly nice test forme to

    0 讨论(0)
提交回复
热议问题