Cheat Sheets
Agile
Containers
DevOps Automation
DevOps Linux
DevOps Services
Glib Examples
Go Examples
Javascript Examples
Languages
PHP Examples
Python Examples
Scripting
Security
Solutions
Virtualization
visual-ops
Apache
CouchDB
Couchbase
ElasticSearch
Eureka
F5
GlusterFS
Hadoop
Java
Kafka
MongoDB
MySQL
NFS
Nodejs
PgBouncer
Postgres
RabbitMQ
Redis
Squid
Tomcat
Webserver
Zookeeper
etcd
htaccess
htaccess Checker
memcached
nginx
sqlite
zuul
AWS - CLI
AWS - Cost
Deis
EC2 API Tools
ESX
Flynn
Heroku
Juju
KVM
LXC
LXD
OpenNebula
OpenStack
OpenVZ
VM Tuning
Vagrant
Vagrantfile
VirtualBox
Xen
heroku
systemd
vSphere
PyGI GStreamer
PyGI GTK Tutorial
PyGI GnomeKeyring
PyGI GtkStatusIcon
PyGObject API
Python Sockets
Python Syntax
Python re.match
Python re.sub
Python simplehttpserver
Python subprocess
Ansible
Bower
Chef
Gerrit
Git
Hubot - Howto
IT-Ops
Jenkins
Maven
Mcollective
Monitoring
Packaging
Puppet
Puppet - Hiera
Puppet - Iterating
Splunk
cfengine
salt
saltstack
CSS
Dev-Misc
GCC
GraphQL
JSON Schema
JSON
Java Debugging
Javascript
Linting
Linux HTML Widgets
Markdown
PHP
Perl
Perl Regex
Python
Regex Overview
Regex101
Ruby
Ruby Bundler
Ruby Regex
SVG Attributes
SVG Elements
Syndication
XHTML
XML 1.0
XML 1.1
XPath
XSD
XSLT 2.0
YAML
autotools
gdb
rvm
Go Channels
Go Goroutines
Go Interfaces
Go Struct
PHP Arrays
PHP curl_setopt
PHP date
PHP explode
PHP implode
PHP ini_set
PHP preg_match
PHP preg_replace
PHP str_replace
PHP stripos
PHP strpos
PHP strripos
PHP strrpos
PHP ternary operator
PHP unserialize
APIs
Bash
Bash Associative Array
Bash Functions
Bash Regex
Color Distance
Shell Problems
Shell-Scripting
awk
packages.json
sed
DBUS
DKMS
DRBD
Debian
Debugging
Filesystem
GPG
IPMI
Kernel Tracing
LVM
Linux Insides
Linux-Commands
Linux-HA
Linux-Networking
Linux-Sysadmin
Linux-Virtualization
Mail
Package Management
Packaging
Partitioning
Quota
RAID
SSH
Solaris
SysRq
Sysctl - Net
UEFI Install
ffmpeg
jq
screen-vs-tmux
sssd
systemd
ulimit
vi
vi - Advanced
Glib
Glib GRegex
Glib Testing
Glib XDG Migration
Docker
Helm
Openshift
kubernetes
rkt
Availability Data
Free Tier Compilation
SaaS Dev Tools
Solutions Automation
Solutions Monitoring
Solutions NoSQL
Solutions Virtualization
Status Pages
Agile Roles
Depth of Kanban
Kanban - Kaizen
Scrum
Scrumban
Semantic Services
Team of Teams
Neighbourhood Network
netstat Dendrogram
netstat Force Graph
netstat Services
AppArmor
HTTPS
Nmap
OpenSSL
Package Vulnerabilities
SELinux
SIEM
SSL-Certificates
Secure REST APIs
Security Auditing
Security-News-Feeds
Session Mgmt
Unhide Processes
Dependency Test
Javascript Singleton
Javascript strptime
Javascript toggle visibility
Javascript void0
Nodejs Compatibility
Nodejs Express
React
React JSX
React PropTypes
React Tutorial
Todo MVC

PHP preg_match Examples

Use preg_match() to match strings with regular expressions. Check the return value for true to see if the expression did match.

1. Syntax of preg_match

While full syntax is
int preg_match ( string $pattern , string $subject 
     [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )
you propably will use preg_match() mostly with two parameters for simply matching checks or with three to extract matches. You probably won't use the 4th and 5th parameter which can be used to return match offsets and limit matching to a given offset in the string.

2. Simple String Checks

Here are some syntax examples that check strings for certain content: Basic matching
preg_match("/PHP/", "PHP")       # Match for an unbound literal
preg_match("/^PHP/", "PHP")      # Match literal at start of string
preg_match("/PHP$/", "PHP")      # Match literal at end of string
preg_match("/^PHP$/", "PHP")     # Match for exact string content
preg_match("/^$/", "")           # Match empty string
Using different regex delimiters
preg_match("/PHP/", "PHP")                # / as commonly used delimiter
preg_match("@[email protected]", "PHP")                # @ as delimiter
preg_match("!PHP!", "PHP")                # ! as delimiter
Changing the delimiter becomes useful in some cases
preg_match("/http:\/\//", "http://");     # match http:// protocol prefix with / delimiter
preg_match("#http://#",   "http://")      # match http:// protocol prefix with # delimiter
Case sensitivity
preg_match("/PHP/", "PHP")                # case sensitive string matching
preg_match("/php/i", "PHP")               # case in-sensitive string matching
Matching with wildcards
preg_match("/P.P/",     "PHP")            # match a single character
preg_match("/P.*P/",    "PHP")            # match multipe characters
preg_match("/P[A-Z]P/", "PHP")            # match from character range A-Z
preg_match("/[PH]*/",   "PHP")            # match from character set P and H
preg_match("/P\wP/",    "PHP")            # match one word character
preg_match("/\bPHP\b/", "regex in PHP")   # match the word "PHP", but not "PHP" as larger string
Using quantifiers
preg_match("/[PH]{3}/",   "PHP")          # match exactly 3 characters from set [PH]
preg_match("/[PH]{3,3}/", "PHP")          # match exactly 3 characters from set [PH]
preg_match("/[PH]{,3}/",  "PHP")          # match at most 3 characters from set [PH]
preg_match("/[PH]{3,}/",  "PHP")          # match at least 3 characters from set [PH]

3. Extracting Data

To extract data using regular expression we have to use capture/grouping syntax.

Some basic examples

# Extract everything after the literal "START"
preg_match("/START(.*)/", $string, $results)   

# Extract the number from a date string 
preg_match("/(\d{4})-(\d{2})-(\d{2})/", "2012-10-20", $results)

# Nesting of capture groups, extract full name, and both parts...
preg_match("/name is ((\w+), (\w+))/", "name is Doe, John", $results)
So you basically just enclose the sub patterns you want to extract with braces and fetch the results by passing a third parameter which preg_match() will fill as an array.

Named Capture Groups

# Extract the number from a date string 
preg_match("/(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})/", "2012-10-20", $results)
Now the $result array will additionally to the position matches 1, 2 and 3 contain the keys "year", "month" and "day". The advantage is never having to think of the capture positions anymore when you modify the expression!

4. Check Processing Errors!

While it might often be unimportant be aware that applying a regular expression might fail due to PCRE constraints. This usually happens when matching overly long strings or strings with faulty encoding. The only way to notice that preg_match() was not able to check the string is by calling
preg_last_error()
Only if it returns PREG_NO_ERROR you got a safe result! Consider this when using preg_match() for security purposes.

5. Suggested Reading

Comment on Disqus
Videos

Learn how to use pgreg_match()

Demystifying Regular Expressions






Related pages