使用 POSIX 字符集集合加速 regex 使用

前言

在開發過程中,經常會遇到資料中包含特殊字元的情況,導致輸出錯誤。解決這個問題的常用方法是使用正規表達式(regex)來過濾字串。但是,需要過濾的字元種類很多,以往都是遇到一個解決一個。
最近我發現,regex 中其實已經定義了許多常用的字元集合,我們可以使用它們來簡化字串過濾的流程。

POSIX Character classes

POSIX 字符集集合是正規表達式(regex)中的一種特殊字符集。透過它可以讓你使用更簡單的方式表示常用的字符集

常用的 POSIX
[:alnum:] Alphanumeric characters
[:alpha:] Alphabetic characters
[:cntrl:] Control characters
[:digit:] Digits
[:lower:] Lowercase letters
[:upper:] Uppercase letters

其他可參考:
https://www.regular-expressions.info/posixbrackets.html

Example

1
2
3
4
$text = "abc123def";
$result = preg_replace("/[[:digit:]]/","", $text);

// abcdef

參考

https://www.regular-expressions.info/posixbrackets.html
https://www.hscripts.com/tutorials/regular-expression/character-classes/control.php
https://stackoverflow.com/questions/1497885/remove-control-characters-from-php-string