PHP - String manipulation remove spcial characters and replace spaces

后端 未结 5 1402
余生分开走
余生分开走 2020-12-15 14:57

I am getting strings from a database and then using the strings to build a URL. My issue is, some of the strings will have characters like < > & { } * general specia

相关标签:
5条回答
  • 2020-12-15 15:19

    1) Replace diacritics with iconv
    2) Replace non letter characters with empty string
    3) Replace spaces with dash
    4) Trim the string for the dash characters (you can also trim the string before manipulations)

    Example, if you use UTF-8 encoding :

    setlocale(LC_ALL, 'fr_CA.utf8');
    $str = "%#dŝdèàâ.,d s#$4.sèdf;21df";
    
    $str = iconv("UTF-8", "ASCII//TRANSLIT", $str); // "%#dsdeaa.,d s#$4.sedf;21df"
    $str = preg_replace("`[^\w]+`", "", $str); // "dsdeaad s4sedf21df"
    $str = str_replace(" ", "-", $str); // "dsdeaad-s4sedf21df"
    $str = trim($str, '-'); // "dsdeaad-s4sedf21df"
    
    0 讨论(0)
  • 2020-12-15 15:20
    $search_value =array(",",".",'"',"'","\\"," ","/","&","[","]","(",")"," 
    {","}",":","`","!","@","#","%","=","+");
    $replace_value =array("-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","- 
    ","-","-","-","-","-");
    $product_name = str_replace($search_value,$replace_value,$row["Product_Name"]);
    $product_name = str_replace("--","-",$product_name);
    $product_name = str_replace("--","-",$product_name);
    $product_name = preg_replace('/-$/', '', $product_name);
    $product_name = preg_replace('/^-/', '', $product_name);
    

    This will create dashed string (Only have alphanumeric character with dash).Useful for create URI strings.

    0 讨论(0)
  • 2020-12-15 15:34
    str_replace(' ','-',$string);
    

    alphanumeric:

    $output = preg_replace("/[^A-Za-z0-9]/","",$input); 
    

    if you want to keep the characters:

     htmlspecialchars($string);
    
    0 讨论(0)
  • 2020-12-15 15:37

    Keep only alphabets and numbers in a string using preg_replace:

    $string = preg_replace('/[^a-zA-Z0-9-]/', '', $string);
    

    You can use str_replace to replace space with -

    $string = str_replace (" ", "-", $string);
    

    Look at the following article:

    • How To Clean Special Characters From PHP String
    0 讨论(0)
  • 2020-12-15 15:38

    With str_replace:

    $str = str_replace(array(' ', '<', '>', '&', '{', '}', '*'), array('-'), $str);
    

    Note:

    If replace has fewer values than search, then an empty string is used for the rest of replacement values.

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