Are you ready for your business to grow? Contact us today to get started!
Please note: this is a very old post, there are most likely updated and more efficient ways to do these functions!

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 ###.###.###.###:

/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/

Match a URL
Matches a valid url, in the format of either http://www.url.com, https://www.url.com, or just www.url.com.  It will also find URLs without the subdomain, so it would match http://url.com, https://url.com and url.com 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]:

/^([a-zA-Z0-9_\.-]+)@([\da-zA-Z\.-]+)\.([a-zA-Z\.]{2,6})$/

 

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!

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

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);

Pin It on Pinterest