17

次のような文字列を取ります。

C#の場合:文字列のコンマ区切りリストで文字列の前後に「引用符」を追加するにはどうすればよいですか?

そしてそれを次のように変換します:

in-c-how-do-i-add-quotes-around-string-in-a-comma-delimited-list-of-strings

要件:

  • 各単語をダッシュ​​で区切り、すべての句読点を削除します(すべての単語がスペースで区切られているわけではないことを考慮に入れてください)。
  • 関数は最大長を受け取り、その最大長未満のすべてのトークンを取得します。例:ToSeoFriendly("hello world hello world", 14)戻り値"hello-world"
  • すべての単語は小文字に変換されます。

別のメモで、最小の長さがあるべきですか?

4

12 に答える 12

10

これがC#での私のソリューションです

private string ToSeoFriendly(string title, int maxLength) {
    var match = Regex.Match(title.ToLower(), "[\\w]+");
    StringBuilder result = new StringBuilder("");
    bool maxLengthHit = false;
    while (match.Success && !maxLengthHit) {
        if (result.Length + match.Value.Length <= maxLength) {
            result.Append(match.Value + "-");
        } else {
            maxLengthHit = true;
            // Handle a situation where there is only one word and it is greater than the max length.
            if (result.Length == 0) result.Append(match.Value.Substring(0, maxLength));
        }
        match = match.NextMatch();
    }
    // Remove trailing '-'
    if (result[result.Length - 1] == '-') result.Remove(result.Length - 1, 1);
    return result.ToString();
}
于 2009-01-21T16:40:57.537 に答える
7

次の手順に従います。

  1. 文字列を小文字に変換する
  2. 不要な文字をハイフンに置き換える
  3. 複数のハイフンを 1 つのハイフンに置き換える (preg_replace()関数呼び出しはすでに複数のハイフンを防止しているため、必要ありません)
  4. 必要に応じて、先頭と末尾のハイフンを削除します
  5. 必要に応じて、位置 x の前の最後のハイフンから最後までトリムします

したがって、関数 (PHP) ですべてまとめて:

function generateUrlSlug($string, $maxlen=0)
{
    $string = trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($string)), '-');
    if ($maxlen && strlen($string) > $maxlen) {
        $string = substr($string, 0, $maxlen);
        $pos = strrpos($string, '-');
        if ($pos > 0) {
            $string = substr($string, 0, $pos);
        }
    }
    return $string;
}
于 2009-01-21T15:40:55.960 に答える
4

C#

public string toFriendly(string subject)
{
    subject = subject.Trim().ToLower();
    subject = Regex.Replace(subject, @"\s+", "-");
    subject = Regex.Replace(subject, @"[^A-Za-z0-9_-]", "");
    return subject;
}
于 2009-01-21T15:53:39.863 に答える
2

より良いバージョン:

function Slugify($string)
{
    return strtolower(trim(preg_replace(array('~[^0-9a-z]~i', '~-+~'), '-', $string), '-'));
}
于 2009-08-08T12:21:00.360 に答える
2

これが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);
}

利用方法:

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

URI を入力可能にする必要がない限り、小さくする必要はありません。ただし、URL がプロキシなどで適切に機能するように、最大​​値を指定する必要があります。

于 2009-01-21T15:22:35.933 に答える
1

Perl での解決策:

my $input = 'In C#: How do I add "Quotes" around string in a comma delimited list of strings?';

my $length = 20;
$input =~ s/[^a-z0-9]+/-/gi;
$input =~ s/^(.{1,$length}).*/\L$1/;

print "$input\n";

終わり。

于 2009-10-02T14:33:15.007 に答える
1

シェルでの解決策:

echo 'In C#: How do I add "Quotes" around string in a comma delimited list of strings?' | \
    tr A-Z a-z | \
    sed 's/[^a-z0-9]\+/-/g;s/^\(.\{1,20\}\).*/\1/'
于 2009-10-02T14:37:28.013 に答える
1

これは、スタック オーバーフローがスラッグを生成する方法に似ています。

public static string GenerateSlug(string title)
{
    string slug = title.ToLower();
    if (slug.Length > 81)
      slug = slug.Substring(0, 81);
    slug = Regex.Replace(slug, @"[^a-z0-9\-_\./\\ ]+", "");
    slug = Regex.Replace(slug, @"[^a-z0-9]+", "-");

    if (slug[slug.Length - 1] == '-')
      slug = slug.Remove(slug.Length - 1, 1);
    return slug;
}
于 2010-11-26T03:34:39.973 に答える
0

Pythonの場合(別のフレームワークを使用している場合でも、djangoがインストールされている場合)。

from django.template.defaultfilters import slugify
slugify("In C#: How do I add "Quotes" around string in a comma delimited list of strings?")
于 2010-11-12T00:43:31.370 に答える
0

少なくとも PHP でこれを行う少しクリーンな方法は次のとおりです。

function CleanForUrl($urlPart, $maxLength = null) {
    $url = strtolower(preg_replace(array('/[^a-z0-9\- ]/i', '/[ \-]+/'), array('', '-'), trim($urlPart)));
    if ($maxLength) $url = substr($url, 0, $maxLength);
    return $url;
}

最初に を実行するtrim()と、後で処理することが少なくなり、 で完全な置換が行われpreg_replace()ます。

これのほとんどを思いついた cg に感謝します: SO の質問名のように、URL に配置する文字列をきれいにする最良の方法は何ですか?

于 2009-02-13T01:04:38.910 に答える
0

Rubyを選択する別の季節、別の理由:)

def seo_friendly(str)
  str.strip.downcase.gsub /\W+/, '-'
end

それで全部です。

于 2010-11-12T00:27:56.447 に答える