Back to the 2023 paper

Module III: Basics of Web Programming

20237m

How to do pattern Matching in PHP?

Worked SolutionAI Assisted

Pattern matching in PHP

PHP does pattern matching mainly with regular expressions, using the PCRE (preg_*) functions. A pattern is written between delimiters, e.g. /pattern/flags.

Main functions

Function Purpose
preg_match(p,p, s, m)‘∣Findsthefirstmatch;returns1/0andfills‘m)` | Finds the first match; returns 1/0 and fills `m
preg_match_all(p,p, s, $m) Finds all matches
preg_replace(p,p, r, $s) Replaces matches
preg_split(p,p, s) Splits a string on a pattern
preg_grep(p,p, arr) Filters array elements that match

Common syntax

  • . any character, \d digit, \w word character, \s whitespace
  • ^ start, $ end
  • * 0+, + 1+, ? 0 or 1, {n,m} range
  • [abc] character class, (a|b) alternation, ( ) capture group
  • Flags: i case-insensitive, m multiline

Examples

<?php
// 1. Simple match
if (preg_match("/web/i", "Web Technology")) {
    echo "Found";
}

// 2. Validate an email
$email = "user@example.com";
if (preg_match("/^[\w.+-]+@[\w-]+\.[a-z]{2,}/i",/i", email)) {
    echo "Valid email";
}

// 3. Extract digits with a capture group
preg_match("/(\d{3})-(\d{4})/", "Call 555-1234", $m);
echo m[1].m[1] . m[2];        // 5551234

// 4. Replace
echo preg_replace("/\s+/", " ", "too    many   spaces");   // too many spaces

// 5. Find all numbers
preg_match_all("/\d+/", "a1 b22 c333", $all);
print_r($all[0]);          // 1, 22, 333
?>

Simple (non-regex) matching

For plain text, use strpos(), str_contains(), str_starts_with(), and strcmp(). Use fnmatch() for shell-style wildcards.

Use preg_* for flexible patterns and the simple functions when a fixed substring is enough (they are faster).

Similar questions

Official AppAndroid App

PYQDeck for Android

Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.