Regex(Regular Expression) in PHP You Should Know

Mohasin Hossain
2 min readJul 16, 2022

--

In this tutorial you are going to learn some regex syntax or pattern and it’s meaning to under regex in PHP. Regex is looking complex but it’s not that much if you can find out the syntax or pattern meaning first. Let’s start.

Most common regex syntax or pattern and their meaning or description

[abc]:A single character of: a, b or c

[^abc]:Any single character except: a, b, or c

[a-z]:Any single character in the range a-z

[a-zA-Z0-9]:Any single character in the range a-z or A-Z or 0–9

^:Start of line

$:End of line

\A:Start of string

\z:End of string

.:Any single character

\s:Any whitespace character

\S:Any non-whitespace character

\d:Any digit

\D:Any non-digit

\w:Any word character (letter, number, underscore)

\W:Any non-word character

\b:Any word boundary

(...):Capture everything enclosed

(a|b):a or b

a?:Zero or one of a

a*:Zero or more of a

a+:One or more of a

a{3}:Exactly 3 of a

a{3,}:3 or more of a

a{3,6}:Between 3 and 6 of a

Some options or flag in regex and their meaning or description

i: case insensitive

m: treat as multi-line string

s: dot matches newline

x: ignore whitespace in regex

A: matches only at the start of string

D: matches only at the end of string

U: non-greedy matching by default

Uses of regex in PHP

  • PHP regular expressions are strings with pattern enclosing in delimiters for example "/pattern/".
  • The preg_match() function searches for a match to a pattern in a string.
  • The preg_match_all() function searches for all matches to a pattern in a string.
  • The preg_replace() function searches a string for matches to a pattern and replaces them with a new string or pattern.

Let’s look into some regex example in PHP

To search based on a regular expression, you use the preg_match() function. For example:

Output:

The preg_match() function returns 1 if there is a match in the $message, 0 if it doesn’t, or false on failure.

To get the text that matches the pattern, you add the third parameter to the preg_match() function like the following example:

Output:

The preg_match_all() function searches for all matches to a regular expression. For example:

Output:

To replace strings that match a regular expression, you use the preg_replace() function. For example:

Output:

In conclusion, regex is not hard as you see, just try to remember the meaning of syntax by practicing. Please feel free to leave a comment if you have any feedback, questions or want me to write about another PHP/Laravel related topic.

--

--

Mohasin Hossain

Senior Software Engineer | Mentor @ADPList | Backend focused | PHP, JavaScript, Laravel, Vue.js, Nuxt.js, MySQL, TDD, CI/CD, Docker, Linux