Skip to content

preg_quote

Introduction

In PHP, regular expressions are an essential tool for manipulating and searching strings. The preg_quote() function is one of the many functions that PHP provides to work with regular expressions. It escapes special characters in a string so they can be used safely within a regex pattern. This article covers the preg_quote() function in detail and demonstrates how to use it effectively.

Understanding the preg_quote() function

The preg_quote() function in PHP quotes regular expression characters in a string. It returns the quoted string. The syntax for using the preg_quote() function is as follows:

Understanding the preg_quote() function

php
preg_quote($str, $delimiter);

Here, $str is the string that is to be quoted, and $delimiter is an optional parameter that specifies the delimiter character to use. If $delimiter is specified, it will also be quoted. Note that the function always returns a string. In PHP 8.1+, passing a non-string value to $str triggers a deprecation warning.

Example Usage

Let's look at an example to understand the usage of the preg_quote() function in PHP:

Example Usage of PHP preg_quote()

php
<?php

$user_input = 'This is a test';
$delimiter = '/';

// Quote the string to safely embed it in a regex pattern
$quoted_input = preg_quote($user_input, $delimiter);

// Build the pattern
$pattern = $delimiter . '^' . $quoted_input . '$' . $delimiter;

if (preg_match($pattern, $user_input)) {
  echo 'Match found.';
} else {
  echo 'No match found.';
}

In the example above, we take a string and use preg_quote() to escape any regex metacharacters it might contain. We then embed the escaped string into a regex pattern. This ensures that characters like ^, $, or . are treated as literal characters rather than regex operators. If the match is found, we print "Match found." Otherwise, we print "No match found."

Conclusion

The preg_quote() function is a reliable way to escape special characters in a string for safe use within regular expressions. It is particularly useful when dynamically building patterns from user input or external data. By using preg_quote(), developers can prevent unintended regex behavior and ensure patterns match exactly as intended. We hope this overview clarifies how to use preg_quote() in your PHP projects.

Practice

What does the preg_quote() function in PHP do?

Dual-run preview — compare with live Symfony routes.