Php Regex Cheat Sheet



Top 15 Commonly Used Regex

  1. Php Replace Regex
  2. Php Regex Cheat Sheet
  3. Php Regex Match
  4. Php Regex Syntax

A simple PHP regex cheat sheet via http://www.php.net/manual/en/function.preg-match.php#105924. What is Regular expression in PHP? PHP Regular Expression also known as regex are powerful pattern matching algorithm that can be performed in a single expression. Regular expressions use arithmetic operators such as (+,-,^) to create complex expressions. They can help you accomplish tasks such as validating email addresses, IP address etc.

Regular Expressions aka Regex are expressions that define a search pattern. They are widely used for validation purposes, like email validation, url validation, phone number validation and so on.

Forming Regex:
A regex is written between two forward slashes (/) delimiters. These delimiters are essential only for certain Regex engines (JS,PHP..). It is then followed by 2 flags:

  • i : Ignore case Flag, ignores the case(uppercase/lowercase) of the input string
  • g : Global Flag, searches for multiple matches instead of stopping at the first match

A quick cheat sheet for those of you who do not remember all the rules of Regex

Regex

Cheat Sheet – Regex Rules

Character classesQuantifiers & Alternation
.any character except newlinea* a+ a?0 or more, 1 or more, 0 or 1
w d sword, digit, whitespacea{5} a{2,}exactly five, two or more
W D Snot word, digit, whitespacea{1,3}between one & three
[abc]any of a, b, or ca+? a{2,}? match as few as possible
[^abc]not a, b, or cab|cdmatch ab or cd
[a-g]character between a & g
AnchorsGroups & Lookaround
^abc$start / end of the string(abc)capture group
bword boundary1backreference to group #1
Escaped characters(?:abc)non-capturing group
. * is used to escape special chars. * matches *(?=abc)positive lookahead
t n rtab, linefeed, carriage return(?!abc)negative lookahead

Commonly used Regex

1. Digits

  • Whole Numbers – /^d+$/
  • Decimal Numbers – /^d*.d+$/
  • Whole + Decimal Numbers – /^d*(.d+)?$/
  • Negative, Positive Whole + Decimal Numbers – /^-?d*(.d+)?$/
  • Whole + Decimal + Fractions – /[-]?[0-9]+[,.]?[0-9]*([/][0-9]+[,.]?[0-9]*)*/

2. Alphanumeric Characters

  • Alphanumeric without space – /^[a-zA-Z0-9]*$/
  • Alphanumeric with space – /^[a-zA-Z0-9 ]*$/

3. Email

  • Common email Ids – /^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,6})*$/
  • Uncommon email ids – /^([a-z0-9_.+-]+)@([da-z.-]+).([a-z.]{2,6})$/

4. Password Strength

  • Complex: Should have 1 lowercase letter, 1 uppercase letter, 1 number, 1 special character and be at least 8 characters long
  • Moderate: Should have 1 lowercase letter, 1 uppercase letter, 1 number, and be at least 8 characters long

5. Username

  • Alphanumeric string that may include _ and – having a length of 3 to 16 characters –
    /^[a-z0-9_-]{3,16}$/

6. URL

  • Include http(s) Protocol

7. IP Address

  • Both IPv4, IPv6 addresses

8. Dates

  • Date Format YYYY-MM-dd using separator -
  • Date Format dd-MM-YYYY using separators - or . or /
  • Date Format dd-mmm-YYYY using separators - or . or /

9. Time

  • Time Format HH:MM 12-hour, optional leading 0
    /^(0?[1-9]|1[0-2]):[0-5][0-9]$/
  • Time Format HH:MM 12-hour, optional leading 0, Meridiems (AM/PM)
    /((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))/
  • Time Format HH:MM 24-hour with leading 0
    /^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
  • Time Format HH:MM 24-hour, optional leading 0
    /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
  • Time Format HH:MM:SS 24-hour
    /(?:[01]d|2[0123]):(?:[012345]d):(?:[012345]d)/

10. HTML Tags

  • Elements with Attributes/</?[ws]*>|<.+[W]>/

11. Javascript Handlers

  • Inline JS handler/bonw+=S+(?=.*>)/
  • Inline JS handler with element/(?:<[^>]+s)(onS+)=[']?((?:.(?![']?s+(?:S+)=|[>']))+.)[']?/

12. Slug

  • Slug/^[a-z0-9]+(?:-[a-z0-9]+)*$/

13. Match Duplicates in a String

  • Search Duplicates/(bw+b)(?=.*b1b)/

14. Phone Numbers

  • International Phone Numbers – with optional country code/extension

Note: Use regex for validating phone numbers only if you don’t have the choice to use a library. There are several libraries that handle phone numbers more accurately and should be used instead.

15. File Path

  • File Path with optional Filename, extension
  • File Name with extension having 3 chars

Additional Regexes

1. Zip codes

There is NO single Regex that can handle all zip codes given that zip codes around the world do not follow a common pattern. Here is a list that contains Regex specific to each country.

2. Payment Validation

Here is a link that contains regex for validating leading Credit cards like Visa, Mastercard and so on.

3. Identity Documents

  • Social Security Number – Ref
  • Passport – /^[A-PR-WY][1-9]ds?d{4}[1-9]$/

References

Php Replace Regex

Php cheat sheet pdf

P.s. Need a graphical explanation of any of the above Regex ? Try Regular Expression Visualization and copy-paste any Regex in the input box to get a graphical representation of it. Hope that helps!

Do you want to write flawless code for your website? Do you want to avoid plodding through multiple rounds of rework? Then, PHP cheat sheet will serve as a nifty productivity tool. It will help you to meet deadlines.

PHP stands for Hypertext Preprocessor. It is a server-side scripting language that is compatible with almost all the web-servers. The most popular language for web development. But, it is difficult for a user to memorize all the PHP code. For solving this problem, PHP cheat sheets are used. A PHP cheat sheet is a reference guide for a user which consists of all the important syntax to accomplish a task. A user can save lots of time using a PHP cheat sheet as no need to search the whole Internet for a small code to perform a specific task. A beginner can have all the PHP codes available in a single document at all times.

PHP Cheat Sheets for Beginners

PHP cheat sheet is a great tool for beginners as they don’t have to cram everything. They can refer a cheat sheet whenever writing scripts in PHP. A number of PHP cheat sheets are available on the internet. But here at TemplateToaster website builder, I made a list of some of the useful popular cheat sheets. Let’s have a look

1. WordPress Help Sheet

A good PHP cheat sheet maintained by Quicklycode. It contains important PHP snippets for the header, basic templates, & other sections. Gives the syntax to specify the title of the site, name of the site, author of the page, the content of post etc. It also provides the information about template file like style.css, index.PHP, page.php and much more. Definitely, a useful PHP resource for beginners.

2. PHP Reference Sheet Basics

It is one of the best PHP cheat sheets that contains a list of all the basic operations performed in PHP. The sections are maintained function-wise. Like data types, array functions, sessions, loops etc. each section includes the data related to the specific function. For example, Data Types section includes a list of valid data types for PHP. Similarly, String Manipulation section contains functions for string operations and so on. It is a smart reference guide for users.

3. PHP Cheat Sheet at Overapi

It’s a detailed PHP cheat sheet. It contains basic functions for arrays, strings, date/time, calendar, file system, maths, error handling etc. Along with basics, it includes directory, HTTP, FTP, MySQLi, Libxml, Parser, ZIP, OOP, miscellaneous functions. It will give you all the brief details about a specific function in a single click.

4. Smarty Cheat Sheet For Template Designers

This PHP cheatsheet is maintained by Hasin Hayder. It is a popular PHP cheat sheet for template designers which includes syntax of main functions while designing a template. Gives information about assigning variables, displaying output, debugging the templates etc. It also specifies common modifiers, passing objects to a template, executing PHP template etc. Includes the built-in functions and custom functions.

5. PHP Cheat Sheet by Daniel

It is a popular PHP cheat sheet by Daniel Dev. Includes functions for MySQL, string, array, classes, and objects, variable handling, output control, regex etc. It also contains the SQLitet3 functions.

6. PHP 4 Reference Card

This PHP cheat sheet is designed by Steven R. Gould. It contains everything from basic functions to file handling functions. Enlists basic syntax, predefined PHP variables, control structures, functions, classes & objects, operators etc. Also includes functions for the file system, session handling, maths and unified ODBC.

7. PHP Cheat Sheet by Dave Child

This PHP cheat sheet is given by Dave Child. It serves as a quick reference guide for beginners. Contains functions for the array, string, regular expression, date formatting, pattern modifier etc. It also includes functions for date and time and file handling. Whenever you click a function, it will display the full description of that function. It will also tell about associated parameters, return values with an example.

8. Web Cheat Sheet

Web Cheat Sheet is like an online PHP manual. It contains all the information from what is PHP to Debugging PHP. Includes all the basic functions plus form handling, cookies, image generation, database linking and much more. It will make you understand everything with examples. A very useful PHP cheat sheet for beginners.

9. 5 Part PHP Cheat Sheet

This PHP cheatsheet covers the all-important details about PHP in 5 parts. It includes PHP basics, PHP modes, PHP functions, PHP commands along with the references to other cheat sheets. PHP functions part consists of functions of strings, maths, random number generation, array, advanced functions. It also made the reference to other useful PHP cheat sheets.

Php Regex Cheat Sheet

10. PHP Quick Reference Card

It’s a useful PHP cheat sheet pdf resource. Includes functions for an array, maths, date & time, output, exception handling, looping, miscellaneous etc. It also contains variables, data types, superglobals etc.

11. PHPUnit Cheat Sheet

Php Regex Match

This is a PHP cheat sheet pdf version 0.1. It contains a list of all the important PHP functions. Enlists every function from objects, classes to template methods, annotations, utilities etc.

12. PHP Regex Cheat Sheet

A regular expression is a sequence of characters for pattern-matching functionality. These are used to search/replace a string inside another string. So, this PHP regex cheat sheet by Dave Child is a reference guide to regular expressions. It includes symbols, ranges, grouping, and some sample patterns. This sheet has different sections for anchors, quantifiers, POSIX, special metacharacters, string replacement etc.

Final Words

Php Regex Syntax

PHP functions handle certain things like managing a string, date, number, loops, etc. But certainly, these are difficult to memorize. So, the enlisted PHP cheat sheets consist of all the important functions for web development. A PHP cheat sheet is a useful resource for a beginner. As some cheat sheets also include the description functions. These are very simple to refer and time-saving. Hence, it serves as a dedicated source to the audience in an approachable & entertaining way.