Skip to content

Chapter 31 of 38

Regular Expressions

Use PCRE patterns, captures, replacement, Unicode, and safe complexity.

38 minutes 10 quick checksBy Subha Prasad
Lesson 31 of 38Course navigation

Lesson content

Read, practise, then check your understanding

PHP uses PCRE through preg_match, preg_match_all, preg_replace, and related functions. Patterns use delimiters and optional modifiers.

Practical example

<?php
if (preg_match('/\A(?<slug>[a-z0-9]+(?:-[a-z0-9]+)*)\z/D', $input, $matches) !== 1) {
  throw new InvalidArgumentException('Invalid slug');
}

Use the u modifier for UTF-8 semantics when required. Check errors, escape dynamic literal fragments with preg_quote, and avoid ambiguous nested quantifiers that can cause denial-of-service backtracking. Use parsers for complex grammars.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes PCRE?
Which PHP term matches this description: The regular-expression engine family used by preg_* functions.
Which statement best describes preg_match?
Which PHP term matches this description: Testing and capturing the first pattern match.
Which statement best describes preg_replace?
Which PHP term matches this description: Replacing pattern matches in strings.
Which statement best describes delimiter?
Which PHP term matches this description: Characters surrounding a PHP regular-expression pattern.
Which statement best describes backtracking?
Which PHP term matches this description: Pattern search behavior that can become expensive for ambiguous repetition.

0 of 10 checks passed

Your progress is saved on this device.