Regular expression - any text to URL friendly one

后端 未结 5 943
一个人的身影
一个人的身影 2020-12-14 23:32

PHP regular expression script to remove anything that is not a alphabetical letter or number 0 to 9 and replace space to a hyphen - change to lowercase make sure there is on

5条回答
  •  天涯浪人
    2020-12-14 23:48

    Since you seem to want all sequences of non-alphanumeric characters being replaced by a single hyphen, you can use this:

    $str = preg_replace('/[^a-zA-Z0-9]+/', '-', $str);
    

    But this can result in leading or trailing hyphens that can be removed with trim:

    $str = trim($str, '-');
    

    And to convert the result into lowercase, use strtolower:

    $str = strtolower($str);
    

    So all together:

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

    Or in a compact one-liner:

    $str = strtolower(trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $str), '-'));
    

提交回复
热议问题