Convert any title to url slug and back from url slug to title

前端 未结 3 1775
梦谈多话
梦谈多话 2021-02-14 21:47

I want to convert any title e.g. of a blog entry to a user friendly url. I used rawurlencode() to do that but it gives me a lot of strange strings like %s.

3条回答
  •  日久生厌
    2021-02-14 22:37

    function url_title($str, $separator = 'dash', $lowercase = FALSE)
     {
      if ($separator == 'dash')
      {
       $search  = '_';
       $replace = '-';
      }
      else
      {
       $search  = '-';
       $replace = '_';
      }
    
      $trans = array(
          '&\#\d+?;'    => '',
          '&\S+?;'    => '',
          '\s+'     => $replace,
          '[^a-z0-9\-\._]'  => '',
          $replace.'+'   => $replace,
          $replace.'$'   => $replace,
          '^'.$replace   => $replace,
          '\.+$'     => ''
           );
    
      $str = strip_tags($str);
    
      foreach ($trans as $key => $val)
      {
       $str = preg_replace("#".$key."#i", $val, $str);
      }
    
      if ($lowercase === TRUE)
      {
       $str = strtolower($str);
      }
    
      return trim(stripslashes($str));
     }
    

提交回复
热议问题