Learn PHP Programming

A backend server scripting language, and a powerful tool for making dynamic and interactive Web pages. Learn each topic with examples and output.

PHP Introduction
Control Structures
Php Forms
Php Advanced

PHP 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 searching for.

A regular expression can be a single character, or a more complicated pattern.

Regular expressions can be used to perform all types of text search and text replace operations.

In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers.

            $exp = "/analyzecode/i";
           

In the example above, / is the delimiter, analyzecode is the pattern that is being searched for, and i is a modifier that makes the search case-insensitive.

The delimiter can be any character that is not a letter, number, backslash or space. The most common delimiter is the forward slash (/), but when your pattern contains forward slashes it is convenient to choose other delimiters such as # or ~.

PHP provides a variety of functions that allow you to use regular expressions. The preg_match(), preg_match_all() and preg_replace() functions are some of the most commonly used ones:

Function Description
preg_match() Returns 1 if the pattern was found in the string and 0 if not
preg_match_all() Returns the number of times the pattern was found in the string, which may also be 0
preg_replace() Returns a new string where matched patterns have been replaced with another string

For example

<?php
// Sample text
$text = "The quick brown fox jumps over the lazy dog. 
        The quick brown dog jumps over the lazy cat.";

// Using preg_match() to find the first occurrence of "fox" or "dog"
$pattern = "/fox|dog/";
if (preg_match($pattern, $text, $matches)) {
    echo "First Match: " . $matches[0] . "\n";
} else {
    echo "No match found.\n";
}

// Using preg_match_all() to find all occurrences of "fox" or "dog"
if (preg_match_all($pattern, $text, $allMatches)) {
    echo "All Matches: " . implode(", ", $allMatches[0]) . "\n";
} else {
    echo "No matches found.\n";
}

// Using preg_replace() to replace "fox" or "dog" with "cat"
$replacementText = preg_replace($pattern, "cat", $text);
echo "Modified Text: " . $replacementText . "\n";
?>

First Match: fox
All Matches: fox, dog
Modified Text: The quick brown cat jumps over the lazy cat. The quick brown cat jumps over the lazy cat.

Now that you have done functions in Php, let's learn functions in php


Share this page on :

=