PHP – Match regular expression using mb_ereg_match()

In PHP, the mb_ereg_match() function is used for matching a given string with a regular expression pattern. This function only matches the string from the beginning and returns true if a match is found, else it returns false. It supports multibyte character sets, making it useful for international text processing.

Syntax

bool mb_ereg_match(string $pattern, string $string, string $options = null)

Parameters

It accepts the following three parameters −

  • $pattern − The regular expression pattern to match against.

  • $string − The input string being evaluated.

  • $options − Optional parameter for search modifiers (e.g., "i" for case-insensitive).

Return Value

The function returns true if the string matches the pattern from the beginning, false otherwise.

Example 1: Basic Pattern Matching

This example demonstrates basic pattern matching from the beginning of a string −

<?php
   // Returns true because "H" is matched at the beginning
   $result = mb_ereg_match("H", "Hello World");
   var_dump($result);

   // Returns false because "H" is not at the beginning
   $output = mb_ereg_match("H", "World Hello");
   var_dump($output);
?>
bool(true)
bool(false)

Example 2: Using Wildcards

To match patterns anywhere in the string, you can use wildcard operators like .*

<?php
   // Matches "e" anywhere in the string
   $result = mb_ereg_match(".*e", "Hello World");
   var_dump($result);

   // Matches exact word pattern
   $result2 = mb_ereg_match("Hello.*", "Hello World");
   var_dump($result2);
?>
bool(true)
bool(true)

Example 3: Case-Insensitive Matching

Using the options parameter for case-insensitive matching −

<?php
   // Case-sensitive (returns false)
   $result1 = mb_ereg_match("hello", "Hello World");
   var_dump($result1);

   // Case-insensitive using "i" option (returns true)
   $result2 = mb_ereg_match("hello", "Hello World", "i");
   var_dump($result2);
?>
bool(false)
bool(true)

Key Points

  • Matches only from the beginning of the string
  • Supports multibyte character encoding
  • Use .* to match patterns anywhere in the string
  • Options parameter allows modifiers like case-insensitive matching

Conclusion

The mb_ereg_match() function is useful for pattern matching with multibyte string support. Remember it only matches from the beginning unless you use wildcards, and the options parameter provides additional flexibility for matching behavior.

Updated on: 2026-03-15T09:59:19+05:30

526 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements