For those who don't want to read themselves into the regular expression syntax I have made a brief compilation of useful snippets in PHP:
Strip unwanted characters
Remove all special characters, except alphabetical (case-insensitive):
$output = preg_replace("/[^a-z]/i", "", $input); |
|
Remove all except digits and alphabetical characters (case-insensitive):
$output = preg_replace("/[^a-z\d]/i", "", $input); |
|
Remove all except digits, alphabetical and spaces (case-insensitive):
$output = preg_replace("/[^a-z \d]/i", "", $input); |
|
Remove excess spaces:
$output = preg_replace('/\s\s+/', ' ', $input); |
|
Make clickable
Make an URL clickable:
$output = preg_replace("#([\t\r\n ])([a-z0-9]+?){1}://([\w\-]+\.([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^ \"\n\r\t<]*)?)#i", '\1<a href="\2://\3" target="_blank" rel="nofollow">\3</a>', $input);
$output = preg_replace("#([\t\r\n ])(www)\.(([\w\-]+\.)*[\w]+(:[0-9]+)?(/[^ \"\n\r\t<]*)?)#i", '\1<a href="http://\2.\3" rel="nofollow" target="_blank">\2.\3</a>', $input);
|
|
Make e-mailaddresses clickable:
$output = preg_replace("#([\n ])([a-z0-9\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)*[\w]+)#i", "\\1<a href=\"mailto:\\2@\\3\" class=orange>\\2@\\3</a>", $input);
|
|
Validation functions
To test if an e-mailaddress is valid:
$test = preg_match("/^[a-z0-9_\.-]+@([a-z0-9]+([\-]+[a-z0-9]+)*\.)+[a-z]{2,7}$/i", $input); |
|
To test if an URL is valid:
$test = preg_match('/(https?:\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i', $input); |
|
Feel free to leave your own useful reg-ex patterns in the comments!