254

URL の問題に直面しています。何かを含む可能性のあるタイトルを変換し、すべての特殊文字を削除して、文字と数字のみが含まれるようにしたいと考えています。もちろん、スペースをハイフンに置き換えたいと考えています。

これはどのように行われますか?正規表現 (regex) が使用されているという話をよく耳にします...

4

3 に答える 3

754

これはあなたが探していることをするはずです:

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

使用法:

echo clean('a|"bc!@£de^&$f g');

出力します:abcdef-g

編集:

簡単な質問ですが、複数のハイフンが隣り合うのを防ぐにはどうすればよいですか? それらは1つだけに置き換えられましたか?

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.

   return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}
于 2013-01-01T21:33:54.827 に答える
128

アップデート

以下のソリューションには、「SEO フレンドリー」バージョンがあります。

function hyphenize($string) {
    $dict = array(
        "I'm"      => "I am",
        "thier"    => "their",
        // Add your own replacements here
    );
    return strtolower(
        preg_replace(
          array( '#[\\s-]+#', '#[^A-Za-z0-9. -]+#' ),
          array( '-', '' ),
          // the full cleanString() can be downloaded from http://www.unexpectedit.com/php/php-clean-string-of-utf8-chars-convert-to-similar-ascii-char
          cleanString(
              str_replace( // preg_replace can be used to support more complicated replacements
                  array_keys($dict),
                  array_values($dict),
                  urldecode($string)
              )
          )
        )
    );
}

function cleanString($text) {
    $utf8 = array(
        '/[áàâãªä]/u'   =>   'a',
        '/[ÁÀÂÃÄ]/u'    =>   'A',
        '/[ÍÌÎÏ]/u'     =>   'I',
        '/[íìîï]/u'     =>   'i',
        '/[éèêë]/u'     =>   'e',
        '/[ÉÈÊË]/u'     =>   'E',
        '/[óòôõºö]/u'   =>   'o',
        '/[ÓÒÔÕÖ]/u'    =>   'O',
        '/[úùûü]/u'     =>   'u',
        '/[ÚÙÛÜ]/u'     =>   'U',
        '/ç/'           =>   'c',
        '/Ç/'           =>   'C',
        '/ñ/'           =>   'n',
        '/Ñ/'           =>   'N',
        '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
        '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
        '/[“”«»„]/u'    =>   ' ', // Double quote
        '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
    );
    return preg_replace(array_keys($utf8), array_values($utf8), $text);
}

上記の関数 (私はかなり非効率的だと思います - 以下の関数の方が優れています)の理論的根拠は、名前を付けてはならないサービスが、URL でスペル チェックとキーワード認識を実行していたようです。

顧客のパラノイアで長い時間を失った後、私は彼らが物事を想像していないことに気づきました.SEOの専門家[私は間違いなくそうではありません]は、たとえば、「Viaggi Economy Perù」をviaggi-economy-peru「より良い振る舞い」に変換すると報告しviaggi-economy-perました.以前の「クリーニング」で UTF8 文字が削除されました(Bogotà はbogotになり、Medellìnはmedellnになりました)。

また、結果に影響していると思われる一般的なスペルミスもいくつかありました。私が理解できる唯一の説明は、URL がアンパックされ、単語が抜き出され、ランキング アルゴリズムを神のみぞ知るのに使用されたということです。そして、これらのアルゴリズムには明らかに UTF8 でクリーン化された文字列が供給されたため、「Perù」は「Per」ではなく「Peru」になりました。「Per」が一致せず、首にかかったようなものです。

UTF8 文字を保持し、いくつかのスペルミスを置き換えるために、以下のより高速な関数がより正確な (?) 関数になりました。$dictもちろん、手作業で調整する必要があります。

前の回答

簡単なアプローチ:

// Remove all characters except A-Z, a-z, 0-9, dots, hyphens and spaces
// Note that the hyphen must go last not to be confused with a range (A-Z)
// and the dot, NOT being special (I know. My life was a lie), is NOT escaped

$str = preg_replace('/[^A-Za-z0-9. -]/', '', $str);

// Replace sequences of spaces with hyphen
$str = preg_replace('/  */', '-', $str);

// The above means "a space, followed by a space repeated zero or more times"
// (should be equivalent to / +/)

// You may also want to try this alternative:
$str = preg_replace('/\\s+/', '-', $str);

// where \s+ means "zero or more whitespaces" (a space is not necessarily the
// same as a whitespace) just to be sure and include everything

urldecode()%20 と + はどちらも実際にはスペースであるため、最初に URL を指定する必要がある場合があることに注意してください。アップ、Never20gonna20give20you20upではありません。あなたはそれを必要としないかもしれませんが、可能性について言及したいと思いました.

したがって、完成した関数とテストケースは次のとおりです。

function hyphenize($string) {
    return 
    ## strtolower(
          preg_replace(
            array('#[\\s-]+#', '#[^A-Za-z0-9. -]+#'),
            array('-', ''),
        ##     cleanString(
              urldecode($string)
        ##     )
        )
    ## )
    ;
}

print implode("\n", array_map(
    function($s) {
            return $s . ' becomes ' . hyphenize($s);
    },
    array(
    'Never%20gonna%20give%20you%20up',
    "I'm not the man I was",
    "'Légeresse', dit sa majesté",
    )));


Never%20gonna%20give%20you%20up    becomes  never-gonna-give-you-up
I'm not the man I was              becomes  im-not-the-man-I-was
'Légeresse', dit sa majesté        becomes  legeresse-dit-sa-majeste

UTF-8 を処理するために、cleanStringオンラインで見つかった実装を使用しました (リンクが壊れていますが、あまり難解ではない UTF8 文字をすべて含む簡略化されたコピーが回答の冒頭にあります。 need) を使用して、UTF8 文字を通常の文字に変換し、「look」という単語を可能な限り保持します。パフォーマンスのために、ここで単純化して関数内にラップすることができます。

上記の関数は小文字への変換も実装していますが、それは好みです。そのためのコードはコメントアウトされています。

于 2013-01-01T21:36:45.050 に答える
52

ここで、この機能をチェックしてください:

function seo_friendly_url($string){
    $string = str_replace(array('[\', \']'), '', $string);
    $string = preg_replace('/\[.*\]/U', '', $string);
    $string = preg_replace('/&(amp;)?#?[a-z0-9]+;/i', '-', $string);
    $string = htmlentities($string, ENT_COMPAT, 'utf-8');
    $string = preg_replace('/&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);/i', '\\1', $string );
    $string = preg_replace(array('/[^a-z0-9]/i', '/[-]+/') , '-', $string);
    return strtolower(trim($string, '-'));
}
于 2013-01-01T21:35:38.153 に答える