views:

40

answers:

4

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 string may also have strings in. How would I replace the spaces with dashes and totally remove and special characters from the strings?

A: 

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:

NAVEED
A: 
str_replace(' ','-',$string);

alphanumeric:

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

if you want to keep the characters:

 htmlspecialchars($string);
Orbit
A: 

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.

Felix Kling
A: 

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"
Vincent Savard