我从数据库中获取字符串,然后使用字符串构建URL。我的问题是,一些字符串将具有像< > &安培; {} *一般特殊字符,但字符串也可能包含字符串。如何用短划线替换空格并完全删除字符串中的特殊字符?
答案 0 :(得分:8)
$string = preg_replace('/[^a-zA-Z0-9-]/', '', $string);
您可以使用str_replace
将空格替换为 -
$string = str_replace (" ", "-", $string);
请看以下文章:
答案 1 :(得分:3)
使用str_replace
:
$str = str_replace(array(' ', '<', '>', '&', '{', '}', '*'), array('-'), $str);
注意:
如果 replace 的值少于 search ,则其余的替换值将使用空字符串。
答案 2 :(得分:2)
1)用iconv替换变音符号
2)用空字符串替换非字母字符
3)用划线灯替换空格
4)修剪短划线字符串(也可以在操作前修剪字符串)
示例,如果您使用UTF-8编码:
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"
答案 3 :(得分:2)
$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);
这将创建虚线字符串(仅包含带有破折号的字母数字字符)。可用于创建URI字符串。
答案 4 :(得分:1)
str_replace(' ','-',$string);
字母
$output = preg_replace("/[^A-Za-z0-9]/","",$input);
如果你想保留字符:
htmlspecialchars($string);