Regular expressions are a very useful tool for developers. They allow to find, identify or replace a word, character or any kind of string. This tutorial will teach you how to master PHP regexp and show you extremely useful, ready-to-use PHP regular expressions that any web developer should have in his toolkit.
Getting Started With Regular Expressions
For many beginners, regular expressions seem to be hard to learn and use. In fact, they’re far less hard than you may think. Before we dive deep inside regexp with useful and reusable codes, let’s quickly see the basics of PCRE regex patterns:
Cheat Sheet This cheat sheet is intended to be a quick reminder for the main concepts involved in using regular expressions and assumes you already understand their usage. If you are new to regular expressions we strongly suggest you work through the Regular Expressions tutorial from the beginning.
- Regular expressions are not as difficult as regex haters make them seem. While regex are intimidating, this cheat sheet will help you overcome that. My experience with regex I have always stayed far away from regex.
- Regular expressions are the default pattern engine in stringr. That means when you use a pattern matching function with a bare string, it’s equivalent to wrapping it in a call to regex: # The regular call: strextract (fruit, 'nana' ) # Is shorthand for strextract (fruit, regex ( 'nana' )).
- Regular expression tester with syntax highlighting, PHP / PCRE & JS Support, contextual help, cheat sheet, reference, and searchable community patterns. RegExr is an online tool to learn, build, & test Regular Expressions (RegEx / RegExp).
- Regular expressions are the default pattern engine in stringr. That means when you use a pattern matching function with a bare string, it’s equivalent to wrapping it in a call to regex: # The regular call: strextract (fruit, 'nana') # Is shorthand for strextract (fruit, regex ('nana')).
Regular Expressions Syntax
A regular expression (regex or regexp for short) is a special text string for describing a search pattern. A regex pattern matches a target string. The following table describes most common regex:
Regular Expression | Will match… |
---|---|
foo | The string “foo” |
^foo | “foo” at the start of a string |
foo$ | “foo” at the end of a string |
^foo$ | “foo” when it is alone on a string |
[abc] | a, b, or c |
[a-z] | Any lowercase letter |
[^A-Z] | Any character that is not a uppercase letter |
(gif|jpg) | Matches either “gif” or “jpg” |
[a-z]+ | One or more lowercase letters |
[0-9.-] | Any number, dot, or minus sign |
^[a-zA-Z0-9_]{1,}$ | Any word of at least one letter, number or _ |
([wx])([yz]) | wy, wz, xy, or xz |
[^A-Za-z0-9] | Any symbol (not a number or a letter) |
([A-Z]{3}|[0-9]{4}) | Matches three letters or four numbers |
PHP Regular Expression Functions
PHP has many useful functions to work with regular expressions. Here is a quick cheat sheet of the main PHP regex functions. Remember that all of them are case sensitive.
For more information about the native functions for PHP regular expressions, have a look at the manual.
Function | Description |
---|---|
preg_match() | The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise. |
preg_match_all() | The preg_match_all() function matches all occurrences of pattern in string. Useful for search and replace. |
preg_replace() | The preg_replace() function operates just like ereg_replace() , except that regular expressions can be used in the pattern and replacement input parameters. |
preg_split() | Preg Split (preg_split() ) operates exactly like the split() function, except that regular expressions are accepted as input parameters. |
preg_grep() | The preg_grep() function searches all elements of input_array , returning all elements matching the regex pattern within a string. |
preg_ quote() | Quote regular expression characters |
Validate a Domain Name
Case sensitive regex to verify if a string is a valid domain name. This is very useful when validating web forms.
» Source
Enlight a Word From a Text
This very useful regular expression will find a specific word in a string and enlight it. Extremely useful for search results. Remember that it’s case sensitive.
» Source
Enlight Search Results in Your WordPress Blog
The previous code snippet can be very handy when it comes to displaying search results. If your website is powered by WordPress, here is a more specific snippet that will search and replace a text by the same text within an HTML tag that you can style later, using CSS.
Open your
search.php
file and find the the_title()
function. Replace it with the following:Now, just before the modified line, add this code:
Save the
search.php
file and open style.css
. Append the following line to it:» Source
Get All Images From a HTML Document
If you ever wanted to be able to get all images form a webpage, this code is a must have for you. You should easily create an image downloader using the power of cURL.
» Source
Remove Repeated Words (Case Insensitive)
Often repeating words while typing? This handy case insensitive PCRE regex will be very helpful.
» Source
Remove Repeated Punctuation
Same php regex as above, but this one will look for repeated punctuation within a string. Goodbye multiple commas!
» Source
Match a XML/HTML Tag
This simple function takes two arguments: The first is the tag you’d like to match, and the second is the variable containing the XML or HTML. Once again, this can be very powerful used along with cURL.
Match an HTML/XML Tag With a Specific Attribute Value
This function is very similar to the previous one, but it allow you to match a tag having a specific attribute. For example, you could easily match
<div>
.Match Hexadecimal Color Values
Another interesting tool for web developers! It allows you to match/validate a hexadecimal color value.
Find Page Title
This handy code snippet will find and print the text within the
<title>
and </title>
tags of a HTML page.Parse Apache Logs
Most websites are running on the Apache webserver. If your website does, you can easily use PHP and regular expressions to parse Apache logs.
» Source
Replace Double Quotes by Smart Quotes
If you’re a typography lover, you’ll probably love this regex pattern which allow you to replace double quotes by smart quotes. A similar regular expression is used by WordPress to make the content more beautiful.
» Source
Check Password Complexity
This regular expression will tests if the input consists of 6 or more letters, digits, underscores, and hyphens.
The input must contain at least one uppercase letter, one lowercase letter and one digit.
The input must contain at least one uppercase letter, one lowercase letter and one digit.
» Source
WordPress: Using Regexp to Retrieve Images From a Post
As I know many of you are WordPress users, you’ll probably enjoy that code which allows you to retrieve all images from post content and display it.
To use this code on your blog, simply paste the following code on one of your theme files.
Generate Emoticons Automatically
Another function used by WordPress. This one allow you to automatically replace an emoticon symbol by an image.
Source:
vignettes/regular-expressions.Rmd
Regular expressions are a concise and flexible tool for describing patterns in strings. This vignette describes the key features of stringr’s regular expressions, as implemented by stringi. It is not a tutorial, so if you’re unfamiliar regular expressions, I’d recommend starting at http://r4ds.had.co.nz/strings.html. If you want to master the details, I’d recommend reading the classic Mastering Regular Expressions by Jeffrey E. F. Friedl.
Regular expressions are the default pattern engine in stringr. That means when you use a pattern matching function with a bare string, it’s equivalent to wrapping it in a call to
regex()
:You will need to use
regex()
explicitly if you want to override the default options, as you’ll see in examples below.Basic matches
The simplest patterns match exact strings:
You can perform a case-insensitive match using
ignore_case = TRUE
:The next step up in complexity is
.
, which matches any character except a newline:You can allow
.
to match everything, including n
, by setting dotall = TRUE
:Escaping
If “
.
” matches any character, how do you match a literal “.
”? You need to use an “escape” to tell the regular expression you want to match it exactly, not use its special behaviour. Like strings, regexps use the backslash,
, to escape special behaviour. So to match an .
, you need the regexp .
. Unfortunately this creates a problem. We use strings to represent regular expressions, and
is also used as an escape symbol in strings. So to create the regular expression .
we need the string '.'
.If
is used as an escape character in regular expressions, how do you match a literal
? Well you need to escape it, creating the regular expression
. To create that regular expression, you need to use a string, which also needs to escape
. That means to match a literal
you need to write '
— you need four backslashes to match one!In this vignette, I use
.
to denote the regular expression, and '.'
to denote the string that represents the regular expression.An alternative quoting mechanism is
Q..E
: all the characters in ..
are treated as exact matches. This is useful if you want to exactly match user input as part of a regular expression.Special characters
Escapes also allow you to specify individual characters that are otherwise hard to type. You can specify individual unicode characters in five ways, either as a variable number of hex digits (four is most common), or by name:
xhh
: 2 hex digits.x{hhhh}
: 1-6 hex digits.uhhhh
: 4 hex digits.Uhhhhhhhh
: 8 hex digits.N{name}
, e.g.N{grinning face}
matches the basic smiling emoji.
Similarly, you can specify many common control characters:
a
: bell.cX
: match a control-X character.e
: escape (u001B
).f
: form feed (u000C
).n
: line feed (u000A
).r
: carriage return (u000D
).0ooo
match an octal character. ‘ooo’ is from one to three octal digits, from 000 to 0377. The leading zero is required.
(Many of these are only of historical interest and are only included here for the sake of completeness.)
Matching multiple characters
There are a number of patterns that match more than one character. You’ve already seen
.
, which matches any character (except a newline). A closely related operator is X
, which matches a grapheme cluster, a set of individual elements that form a single symbol. For example, one way of representing “á” is as the letter “a” plus an accent: .
will match the component “a”, while X
will match the complete symbol:There are five other escaped pairs that match narrower classes of characters:
d
: matches any digit. The complement,D
, matches any character that is not a decimal digit.Technically,d
includes any character in the Unicode Category of Nd (“Number, Decimal Digit”), which also includes numeric symbols from other languages:s
: matches any whitespace. This includes tabs, newlines, form feeds, and any character in the Unicode Z Category (which includes a variety of space characters and other separators.). The complement,S
, matches any non-whitespace character.p{property name}
matches any character with specific unicode property, likep{Uppercase}
orp{Diacritic}
. The complement,P{property name}
, matches all characters without the property. A complete list of unicode properties can be found at http://www.unicode.org/reports/tr44/#Property_Index.w
matches any “word” character, which includes alphabetic characters, marks and decimal numbers. The complement,W
, matches any non-word character.Technically,w
also matches connector punctuation,u200c
(zero width connector), andu200d
(zero width joiner), but these are rarely seen in the wild.b
matches word boundaries, the transition between word and non-word characters.B
matches the opposite: boundaries that have either both word or non-word characters on either side.
You can also create your own character classes using
[]
:[abc]
: matches a, b, or c.[a-z]
: matches every character between a and z (in Unicode code point order).[^abc]
: matches anything except a, b, or c.[^-]
: matches^
or-
.
There are a number of pre-built classes that you can use inside
[]
:[:punct:]
: punctuation.[:alpha:]
: letters.[:lower:]
: lowercase letters.[:upper:]
: upperclass letters.[:digit:]
: digits.[:xdigit:]
: hex digits.[:alnum:]
: letters and numbers.[:cntrl:]
: control characters.[:graph:]
: letters, numbers, and punctuation.[:print:]
: letters, numbers, punctuation, and whitespace.[:space:]
: space characters (basically equivalent tos
).[:blank:]
: space and tab.
These all go inside the
[]
for character classes, i.e. [[:digit:]AX]
matches all digits, A, and X.You can also using Unicode properties, like
[p{Letter}]
, and various set operations, like [p{Letter}--p{script=latin}]
. See ?'stringi-search-charclass'
for details.Alternation
|
is the alternation operator, which will pick between one or more possible matches. For example, abc|def
will match abc
or def
.Note that the precedence for
|
is low, so that abc|def
matches abc
or def
not abcyz
or abxyz
.Grouping
You can use parentheses to override the default precedence rules:
Parenthesis also define “groups” that you can refer to with backreferences, like
1
, 2
etc, and can be extracted with str_match()
. For example, the following regular expression finds all fruits that have a repeated pair of letters:You can use
(?:..)
, the non-grouping parentheses, to control precedence but not capture the match in a group. This is slightly more efficient than capturing parentheses.This is most useful for more complex cases where you need to capture matches and control precedence independently.
Anchors
By default, regular expressions will match any part of a string. It’s often useful to anchor the regular expression so that it matches from the start or end of the string:
^
matches the start of string.$
matches the end of the string.
To match a literal “$” or “^”, you need to escape them,
$
, and ^
.For multiline strings, you can use
regex(multiline = TRUE)
. This changes the behaviour of ^
and $
, and introduces three new operators:![Sheet Sheet](/uploads/1/3/7/3/137353452/887109638.jpg)
^
now matches the start of each line.$
now matches the end of each line.A
matches the start of the input.z
matches the end of the input.Z
matches the end of the input, but before the final line terminator, if it exists.
Perl Regex Cheat Sheet Pdf
Repetition
You can control how many times a pattern matches with the repetition operators:
?
: 0 or 1.+
: 1 or more.*
: 0 or more.
Note that the precedence of these operators is high, so you can write:
colou?r
to match either American or British spellings. That means most uses will need parentheses, like bana(na)+
.You can also specify the number of matches precisely:
{n}
: exactly n{n,}
: n or more{n,m}
: between n and m
By default these matches are “greedy”: they will match the longest string possible. You can make them “lazy”, matching the shortest string possible by putting a
?
after them:![Cheat Cheat](/uploads/1/3/7/3/137353452/589383364.png)
??
: 0 or 1, prefer 0.+?
: 1 or more, match as few times as possible.*?
: 0 or more, match as few times as possible.{n,}?
: n or more, match as few times as possible.{n,m}?
: between n and m, , match as few times as possible, but at least n.
You can also make the matches possessive by putting a
+
after them, which means that if later parts of the match fail, the repetition will not be re-tried with a smaller number of characters. This is an advanced feature used to improve performance in worst-case scenarios (called “catastrophic backtracking”).?+
: 0 or 1, possessive.++
: 1 or more, possessive.*+
: 0 or more, possessive.{n}+
: exactly n, possessive.{n,}+
: n or more, possessive.{n,m}+
: between n and m, possessive.
A related concept is the atomic-match parenthesis,
(?>..)
. Cisco webex app download. If a later match fails and the engine needs to back-track, an atomic match is kept as is: it succeeds or fails as a whole. Compare the following two regular expressions:The atomic match fails because it matches A, and then the next character is a C so it fails. The regular match succeeds because it matches A, but then C doesn’t match, so it back-tracks and tries B instead.
Look arounds
Regular Expression Cheat Sheet
These assertions look ahead or behind the current match without “consuming” any characters (i.e. changing the input position).
(?=..)
: positive look-ahead assertion. Matches if..
matches at the current input.(?!..)
: negative look-ahead assertion. Matches if..
does not match at the current input.(?<=..)
: positive look-behind assertion. Matches if..
matches text preceding the current position, with the last character of the match being the character just before the current position. Length must be bounded
(i.e. no*
or+
).(?<!..)
: negative look-behind assertion. Matches if..
does not match text preceding the current position. Length must be bounded
(i.e. no*
or+
).
R Regex Cheatsheet
These are useful when you want to check that a pattern exists, but you don’t want to include it in the result: