PHP TUTORIALPHP TutorialPHP InstallationPHP Hello WorldPHP Basic SyntaxPHP CommentsPHP VariablesPHP Variable ScopePHP ConstantsPHP StringsPHP OutputPHP Data TypesPHP Type CastingPHP OperatorsPHP ConditionalsPHP Shorthand ConditionalsPHP LoopsPHP Loop Control StructuresPHP FunctionsPHP String FunctionsPHP ArraysPHP Superglobal VariablesPHP in HTMLPHP AdvancedPHP Include and RequirePHP HTTP & HTTPSPHP RegexRegex IntroductionRegex PCRE SyntaxPHP PREG FunctionsPHP FormsPHP Forms IntroductionPHP Forms CreatingPHP Forms SecurityPHP Forms ValidationPHP Forms Required InputsPHP Forms StickyPHP Forms Advanced ValidationPHP Forms FinishingPHP OOPPHP OOP IntroductionPHP OOP ClassesPHP OOP PropertiesPHP OOP ObjectsPHP OOP MethodsPHP OOP $this KeywordPHP OOP Constructors and DestructorsPHP OOP VisibilityPHP OOP InheritancePHP OOP Abstract Classes and MethodsPHP OOP InterfacesPHP OOP TraitsPHP OOP ConstantsPHP OOP StaticPHP OOP NamespacesPHP OOP Autoloading

PHP PREG Functions

PHP has several functions to work with PCRE regular expressions we learned in the last chapter.

Among them, we have already learned about preg_replace() function in PHP. Now we are going to discuss about two of preg_ functions which we will use in PHP forms chapter.


preg_match() function performs a regular expression match.

preg_match() Syntax

preg_match(pattern, input string, variable to save results)

Let's see some examples.

1. Find the word "dogs" in a string

$str = 'She had stood between the pack of wild dogs and what they wanted';
if (preg_match('/\bdogs\b/i', $str)) {
	echo 'Word dogs was found';
} else {
	echo 'Word dogs was not found';

echo "<br>"; // line break

// hotdogs will not match for dogs, because regex matches for word boundaries (\b)
$str = 'Linda returned with two hotdogs and handed one to each of them';
if (preg_match('/\bdogs\b/i', $str)) {
	echo 'Word dogs was found';
} else {
	echo 'Word dogs was not found';

Run Example ››
\b matches a word boundary and the i modifier makes the match case-insensitive.

2. Getting the domain name out of a URL

$url = '';
preg_match('#^(?:\w+://)?([^/]+)#i', $url, $matches);

echo $matches[1];

Run Example ››

Note: Any match inside parentheses is captured. It will be saved in $matches from the index 1. ($matches[1] is the first capture). To avoid capturing of a parenthesized sub pattern, ?: should be appended to the parentheses. ((?:\w+//))

How this regular expressions works:

  • We use # as delimiters.
  • ^ matches for the beginning of the string.
  • (?:\w+://) is a non-capturing parenthesized sub pattern, which matches 1 or more \w (word characters) and ://. (It matches the protocol, which we do not need to capture to get the domain.)
  • ? after the non-capturing sub pattern tells that main pattern should match even the protocol is not defined (0 or 1).
  • ([^/]+) is a capturing sub pattern which matches 1 or more non-front-slash (/) characters, which is the domain.
  • So, any character after a \ is not matched.

Note: $matches[0] saves the full match.

3. Using named sub patterns

In this example, we will use named sub patterns. (?P<book> to name the sub pattern as book)

$str = 'The Mother: Maxim Gorky - 1906';
preg_match('/(?P<book>[\w\s]+): (?P<author>[\w\s]+) - (?P<year>\d+)/', $str, $matches);

echo 'Book: ' . $matches['book'] . '<br>';
echo 'Author: ' . $matches['author'] . '<br>';
echo 'Year: ' . $matches['year'];

Run Example ››


preg_replace() function performs a regular expression match and replace.

preg_replace Syntax

preg_replace(pattern, replace with, input string)

In the following example, all the digits are replaced with $ signs.

preg_replace Example

$str = 'October 22, 2000';
echo preg_replace('/\d/', '$', $str);

Run Example ››
Visit PHP Help group to get some help from experts.
Profile Picture
Supun Kavinda
I'm the Founder of Hyvor, Web Developer, Physics Lover, Flutist, and a Table Tennis Player.
My Websites