24

文字列をURLにサニタイズしたいので、これが基本的に必要なものです:

  1. 英数字とスペースとダッシュを除くすべてを削除する必要があります。
  2. スペースはダッシュに変換する必要があります。

例えば。

This, is the URL!

返さなければならない

this-is-the-url
4

10 に答える 10

51
function slug($z){
    $z = strtolower($z);
    $z = preg_replace('/[^a-z0-9 -]+/', '', $z);
    $z = str_replace(' ', '-', $z);
    return trim($z, '-');
}
于 2010-06-11T11:14:21.360 に答える
4

最初に不要な文字を取り除きます

$new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);

次に、アンサースコアのスペースを変更します

$url = preg_replace('/\s/', '-', $new_string);

最後に、使用できるようにエンコードします

$new_url = urlencode($url);
于 2010-06-11T11:20:45.603 に答える
1

OPはスラッグのすべての属性を明示的に説明しているわけではありませんが、これは私が意図から収集しているものです.

完璧で有効な凝縮されたスラッグの私の解釈は、この投稿と一致しています: https://wordpress.stackexchange.com/questions/149191/slug-formatting-acceptable-characters#:~:text=However%2C%20we%20can% 20summarise%20the、または%20end%20with%20a%20ハイフン

これを一貫して達成するための以前に投稿された回答は見つかりません(また、マルチバイト文字を含めるために質問の範囲を拡大することさえしていません)。

  1. すべての文字を小文字に変換する
  2. 1 つ以上の非英数字のすべてのシーケンスを 1 つのハイフンに置き換えます。
  3. 文字列から先頭と末尾のハイフンを削除します。

使い捨て変数の宣言を気にしない次のワンライナーをお勧めします。

return trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($string)), '-');

また、他の回答で不正確であると私が考えるものを強調するデモンストレーションも用意しました。(デモ)

'This, is - - the URL!' input
'this-is-the-url'       expected

'this-is-----the-url'   SilentGhost
'this-is-the-url'       mario
'This-is---the-URL'     Rooneyl
'This-is-the-URL'       AbhishekGoel
'This, is - - the URL!' HelloHack
'This, is - - the URL!' DenisMatafonov
'This,-is-----the-URL!' AdeelRazaAzeemi
'this-is-the-url'       mickmackusa

---
'Mork & Mindy'      input
'mork-mindy'        expected

'mork--mindy'       SilentGhost
'mork-mindy'        mario
'Mork--Mindy'       Rooneyl
'Mork-Mindy'        AbhishekGoel
'Mork & Mindy'  HelloHack
'Mork & Mindy'      DenisMatafonov
'Mork-&-Mindy'      AdeelRazaAzeemi
'mork-mindy'        mickmackusa

---
'What the_underscore ?!?'   input
'what-the-underscore'       expected

'what-theunderscore'        SilentGhost
'what-the_underscore'       mario
'What-theunderscore-'       Rooneyl
'What-theunderscore-'       AbhishekGoel
'What the_underscore ?!?'   HelloHack
'What the_underscore ?!?'   DenisMatafonov
'What-the_underscore-?!?'   AdeelRazaAzeemi
'what-the-underscore'       mickmackusa
于 2020-12-13T21:36:48.840 に答える
-1

slugify パッケージを使用し、車輪を再発明しないでください ;)

https://github.com/cocur/slugify

于 2020-03-26T13:58:40.143 に答える