文字と数字以外の文字をすべてハイフンに置き換えます [重複] 質問する

文字と数字以外の文字をすべてハイフンに置き換えます [重複] 質問する

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

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

ベストアンサー1

これであなたが探しているものが実現するはずです:

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.
}

おすすめ記事