PHP Regular Expressions (regexp/PCRE)

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Syntax

  • preg_replace($pattern, $replacement, $subject, $limit = -1, $count = 0);
  • preg_replace_callback($pattern, $callback, $subject, $limit = -1, $count = 0);
  • preg_match($pattern, $subject, &$matches, $flags = 0, $offset = 0);
  • preg_match_all($pattern, $subject, &$matches, $flags = PREG_PATTERN_ORDER, $offset = 0);
  • preg_split($pattern, $subject, $limit = -1, $flags = 0)

Parameters

ParameterDetails
$patterna string with a regular expression (PCRE pattern)

Remarks

PHP regular expressions follow PCRE pattern standards, which are derived from Perl regular expressions.

All PCRE strings in PHP must be enclosed with delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character. Popular delimiters are ~, /, % for instance.

PCRE patterns can contain groups, character classes, character groups, look-ahead/look-behind assertions and escaped characters.

It is possible to use PCRE modifiers in the $pattern string. Some common ones are i (case insensitive), m (multiline) and s (the dot metacharacter includes newlines). The g (global) modifier is not allowed, you will use the preg_match_all function instead.

Matches to PCRE strings are done with $ prefixed numbered strings:

<?php

$replaced = preg_replace('%hello ([a-z]+) world%', 'goodbye $1 world', 'hello awesome world');

echo $replaced; // 'goodbye awesome world'


Got any PHP Question?