首頁  >  文章  >  後端開發  >  如何使用正規表示式刪除非字母數字字元並用連字號替換空格?

如何使用正規表示式刪除非字母數字字元並用連字號替換空格?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-23 22:05:29660瀏覽

How to Strip Non-Alphanumeric Characters and Replace Spaces with Hyphens Using Regular Expressions?

剝離非字母數字字元並用連字取代空格

問題:使用者在將標題轉換為URL​​ 時面臨挑戰僅包含字母、數字和連字符。他們尋求一種方法來去除特殊字元並用連字符替換空格。

解決方案:正規表示式(Regex)

正規表示式是模式比對和字串的強大工具操縱。它們可用於實現所需的轉換。

程式碼:

<code class="php">function clean($string) {
    // Replace spaces with hyphens
    $string = str_replace(' ', '-', $string);
    
    // Remove non-alphanumeric characters and hyphens
    $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
    
    // Replace multiple hyphens with a single one
    $string = preg_replace('/-+/', '-', $string);
    
    return $string;
}</code>

用法:

<code class="php">echo clean('a|"bc!@£de^&amp;$f g');</code>

輸出:

其他修改:

為了防止多個連字符連續出現,請替換最後一行clean 函數的:

以上是如何使用正規表示式刪除非字母數字字元並用連字號替換空格?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn