Search⌘ K
AI Features

Regular Expressions in PHP

Explore how to use regular expressions in PHP for efficient text searching and replacement. Understand pattern basics, and learn to apply preg_match and preg_replace functions to match and modify strings effectively.

In this lesson, we’ll use preg_match() and preg_replace() to perform simple pattern matching. We’ll cover the following:

  • What is a regular expression?
  • preg_match()
  • preg_replace()
  • Example

What is a regular expression?

A regular expression is a pattern used to search text. In PHP, regular expressions are commonly used with functions that begin with preg_.

preg_match()

The preg_match() function checks whether a pattern exists in a string.

PHP
<?php
$text = "Order 123 was shipped";
if (preg_match('/\d+/', $text)) {
echo "A number was found";
}
?>

In the code above, /\d+/ matches one or more digits.

preg_replace()

The preg_replace() function replaces text that matches a pattern.

PHP
<?php
$text = "Order 123 was shipped";
echo preg_replace('/\d+/', '456', $text);
?>

Example

The following example checks whether a string starts with the word PHP.

PHP
<?php
$text = "PHP is fun";
if (preg_match('/^PHP/', $text)) {
echo "The string starts with PHP";
}
?>

Explanation

  • ^ represents the start of the string

  • PHP is the text we want to match

Regular expressions in PHP help us search and replace text patterns efficiently.