文字列をURLにサニタイズしたいので、これが基本的に必要なものです:
- 英数字とスペースとダッシュを除くすべてを削除する必要があります。
- スペースはダッシュに変換する必要があります。
例えば。
This, is the URL!
返さなければならない
this-is-the-url
文字列をURLにサニタイズしたいので、これが基本的に必要なものです:
例えば。
This, is the URL!
返さなければならない
this-is-the-url
function slug($z){
$z = strtolower($z);
$z = preg_replace('/[^a-z0-9 -]+/', '', $z);
$z = str_replace(' ', '-', $z);
return trim($z, '-');
}
最初に不要な文字を取り除きます
$new_string = preg_replace("/[^a-zA-Z0-9\s]/", "", $string);
次に、アンサースコアのスペースを変更します
$url = preg_replace('/\s/', '-', $new_string);
最後に、使用できるようにエンコードします
$new_url = urlencode($url);
OPはスラッグのすべての属性を明示的に説明しているわけではありませんが、これは私が意図から収集しているものです.
完璧で有効な凝縮されたスラッグの私の解釈は、この投稿と一致しています: https://wordpress.stackexchange.com/questions/149191/slug-formatting-acceptable-characters#:~:text=However%2C%20we%20can% 20summarise%20the、または%20end%20with%20a%20ハイフン。
これを一貫して達成するための以前に投稿された回答は見つかりません(また、マルチバイト文字を含めるために質問の範囲を拡大することさえしていません)。
使い捨て変数の宣言を気にしない次のワンライナーをお勧めします。
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
slugify パッケージを使用し、車輪を再発明しないでください ;)