I’m currently learning PHP and learning trying to get a string from user inputted data and insert it into the database, to use as a link for post on the site.
I’m using regular expressions in a function to alter the string like so:
function clean_url($string) {
$string = preg_replace('/[^a-z0-9-]+/','-',strtolower($string)); // allows only characters from a-z and 0-9 and converts string to lower case
$string = preg_replace('/-$/', '-', $string); // replace dash -
$string = preg_replace('/--+/','',$string); // replaces double dashes with a single dash
$string = preg_replace('/^-/', '', $string); // replace dash
return $string;
}
I’d like to combine all the regular expressions to one meaningful regex. With these rules in mind
- only characters from a-z and 0-9 are allowed i.e no characters aside – are allowed
- replaces all the – and the beginning and ending of the string with nothing.
- replace all the double dashes — with a single dash.
2
Answers
preg_replace()
accepts arrays as arguments, so one way to do it is:Personally, I prefer your original function with each expression on its own as it makes the code more readable. I would also consider using
str_replace()
for the simple replacementsIf you dont want any
-
characters on the end of the beginning of the string you can usetrim()
.For the double dash replacement you can use
str_replace()
and for the numeric and alpabethic characters you can usepreg_replace()
.