开发者

PHP - String manipulation remove spcial characters and replace spaces

开发者 https://www.devze.com 2023-01-21 10:59 出处:网络
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 special characters, but the s开发者

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 special characters, but the s开发者_如何学编程tring may also have strings in. How would I replace the spaces with dashes and totally remove and special characters from the strings?


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


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.


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"


$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.


str_replace(' ','-',$string);

alphanumeric:

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

if you want to keep the characters:

 htmlspecialchars($string);
0

精彩评论

暂无评论...
验证码 换一张
取 消