I have framework I created and I've created a few 'helper' functions. One function is converting a user entered title (actually a blog post title) I am storing the title and also storing a 'seo_title' the blog post is pulled based on the url entered.

So, when some goes to mysite com/this-is-a-sef-url it uses 'this-is-a-sef-url' to get that blog post.
Anyway here is the function I use to convert:

function convert_to_sef_url($str) {
	$str = str_replace("'","",$str); //replace ' with nothing
	$str = str_replace('"',"",$str); //replace " with nothing
	$str = preg_replace("/[^a-zA-Z0-9_-]/","-", $str); //convert non alphanumeric and non - _ to -
	$str = preg_replace ( "/-+/" , "-" , $str ); //convert multiple dashes to a single dash
	$str = strtolower($str);
	return $str;
}

It works great. can anyone think of a more efficient way or find any bugs?
I want to make sure only a-z and A-Z and 0-9 and underscores and dashes are the only things allowed in the sef url and no multiple dashes. I think I've got everything but a fresh pair of eyes is always nice.

    Untested:

    function convert_to_sef_url($str)
    {
       $regexp = array(
          '/[\'"]/' => '',
          '/[^a-z0-9_-]+/' => '-'
       );
       return strtolower(preg_replace(array_keys($regexp), $regexp, $str));
    }
    

      Slight modification to eliminate multiple consecutive hyphens:

      function convert_to_sef_url($str)
      {
         $regexp = array(
            '/[\'"]/' => '',
            '/([^a-z0-9_-]|-)+/' => '-'
         );
         return strtolower(preg_replace(array_keys($regexp), $regexp, $str));
      }
      

        awesome thanks I had to mod it a little bit:

        function convert_to_sef_url($str)
        {
           $regexp = array(
              '/[\'"]/' => '',
              '/[^a-zA-Z0-9_-]/' => '-'
           );
           return trim(strtolower(preg_replace(array_keys($regexp), $regexp, $str)),'-');
        }

        I added A-Z because it was replacing the uppercase letter with dashes and I added the trim because I didn't want the first or last character to be a dash.

        That is so much nicer then my original thank you NogDog

          Oops, I had meant to add the "i" case-insensitive modifier to the regexp:

          '/([^a-z0-9_-]|-)+/[color=red][b]i[/b][/color]' => '-'
          

            ah. Thank you so much for taking the time to review this function. I really appreciate it.

              Write a Reply...