How can I create a SEO friendly dash-delimited url from a string?

后端 未结 12 1539
再見小時候
再見小時候 2020-12-05 19:16

Take a string such as:

In C#: How do I add \"Quotes\" around string in a comma delimited list of strings?

and convert it to:

12条回答
  •  孤城傲影
    2020-12-05 20:03

    Here's a solution for php:

    function make_uri($input, $max_length) {
      if (function_exists('iconv')) {  
        $input = @iconv('UTF-8', 'ASCII//TRANSLIT', $input);  
      }
    
      $lower = strtolower($input);
    
    
      $without_special = preg_replace_all('/[^a-z0-9 ]/', '', $input);
      $tokens = preg_split('/ +/', $without_special);
    
      $result = '';
    
      for ($tokens as $token) {
        if (strlen($result.'-'.$token) > $max_length+1) {
          break;
        }
    
        $result .= '-'.$token;       
      }
    
      return substr($result, 1);
    }
    

    usage:

    echo make_uri('In C#: How do I add "Quotes" around string in a ...', 500);
    

    Unless you need the uris to be typable, they don't need to be small. But you should specify a maximum so that the urls work well with proxies etc.

提交回复
热议问题