PHP – Match regular expression using mb_ereg_match()

PHPServer Side ProgrammingProgramming

In PHP, 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 of the string and it is not necessary that it will match the string till the end. This function will return true or 1 if a match is found, else it will return False or 0.

Syntax

bool mb_ereg_match(str $pattern, str $string, str $options)

Parameters

It accepts the following three parameters −

  • $pattern − This parameter is used for the regular expression.

  • $string − This parameter is being evaluated.

  • $options − It is used for the search.

Return Values

mb_ereg_match() returns true or 1 if the given string matches the regular expression pattern. If it does not match, then it will return False or 0.

Example 1

<?php
   //It will return True because H is matched
   $result = mb_ereg_match("H", "Hello World");
   var_dump($result);

   //It will return Frue because H is not matched
   $output= mb_ereg_match("H", "World");
   var_dump($output);
?>

Output

bool(true)
bool(false)

Note − In this example, it will only match the string from the beginning but it is not necessary that it will match the string till the end.

If you want to match the string anywhere in the given string, then you can use the wildcard and repeat operators .*. See the next example.

Example 2

<?php
   $result = mb_ereg_match(".*e", "Hello World");
   var_dump($result);
?>

Output

bool(true)
raja
Published on 11-Oct-2021 12:53:09
Advertisements