HOME HTML EDITOR C JAVA PHP

PHP Regular Expressions (RegEx)

A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are looking for.

1. RegEx Functions

PHP provides several functions that allow you to use regular expressions. The most common ones are:

2. preg_match() Example

The preg_match() function tells you whether a string contains matches of a pattern.

<?php
  $str = "Visit ExpertsJava";
  $pattern = "/expertsjava/i";

  echo preg_match($pattern, $str); // Outputs: 1
?>

3. RegEx Modifiers

Modifiers can change how a search is performed. Common modifiers include:

4. preg_replace() Example

The preg_replace() function replaces all matches of a pattern in a string with another string.

<?php
  $str = "Visit Microsoft!";
  $pattern = "/microsoft/i";

  echo preg_replace($pattern, "ExpertsJava", $str);
  // Outputs: Visit ExpertsJava!
?>

5. RegEx Patterns (Meta-characters)

Meta-characters are characters with a special meaning:

Tip: The forward slashes / at the start and end of the pattern are called delimiters. They tell PHP where the expression starts and ends.