More useful regex expressions

More useful regex expressions

Regular expressions are very handy for extracting text, verifying text and manipulating text.  Below you will find some more handy regex expressions:

Match an IP Address
Matches valid IP addresses in format ###.###.###.###:


Match a URL
Matches a valid url, in the format of either,, or just  It will also find URLs without the subdomain, so it would match, and as well.

/^(https?:\/\/)?([\da-zA-Z\.-]+)\.([a-zA-Z\.]{2,6})([\/\w \.-]*)*\/?$/

Match an Email Address
Matches an email address in the format of [email protected]:



Strip non-standard characters
Have you ever had an issue with strange characters appearing in your text?  Most of the time it can be solved by setting the proper character set, however, there are times when it seems like nothing works… for some reason the normal simple regex expressions that should remove all of the junk just do not work.  If that is the case, here is a long expression with all of the valid characters listed.  When nothing else works, this will!


Below is how to use it in your PHP code.  It will keep any character that is on your keyboard, A-Z, 0-9, and all of the extended characters like !@#$%^&*(){}[]\|, etc., and it will also keep new lines/returns and tabs.  Anything else will be removed.

// Remove all non-standard characters
$string = preg_replace("/[^A-Za-z0-9\s\s+\.\:\-\_\^\/%+\(\)\*\&\$\#\!\~\`\|\?\[\]\{\}\@\"\';\>\<\=\n\t\r]/","",$string);