skip to Main Content

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

  1. only characters from a-z and 0-9 are allowed i.e no characters aside – are allowed
  2. replaces all the – and the beginning and ending of the string with nothing.
  3. replace all the double dashes — with a single dash.

2

Answers


  1. preg_replace() accepts arrays as arguments, so one way to do it is:

    $string = preg_replace(array('/[^a-z0-9-]+/','/-$/','/--+/','/^-/'),array('-','-','',''),strtolower($string));
    

    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 replacements

    Login or Signup to reply.
  2. If you dont want any - characters on the end of the beginning of the string you can use trim().

    For the double dash replacement you can use str_replace() and for the numeric and alpabethic characters you can use preg_replace().

    function clean_url($string) {
      return trim(str_replace('--', '-', preg_replace('/[^a-z0-9-]+/','-', strtolower($string))), '-');
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search