PHP Regular Expressions (RegEx)
Regular expressions are patterns used to match character combinations in strings. In PHP, regular expressions are implemented using the PCRE (Perl Compatible Regular Expressions) library.
Regular Expression Syntax
Regular expressions use special characters to define patterns. Here are some common characters:
.
: Matches any single character except newline.^
: Matches the start of a string.$
: Matches the end of a string.*
: Matches 0 or more occurrences of the preceding element.+
: Matches 1 or more occurrences of the preceding element.?
: Matches 0 or 1 occurrence of the preceding element.[abc]
: Matches any one of the enclosed characters (a, b, or c).[^abc]
: Matches any character not enclosed.(...)
: Groups patterns together.|
: Acts as a logical OR between expressions.
Common Functions
preg_match()
: Performs a regular expression match.preg_match_all()
: Performs a global regular expression match.preg_replace()
: Performs a search and replace using a regular expression.preg_split()
: Splits a string by a regular expression.
Example of Using preg_match()
<?php
$pattern = "/^Hello/";
$string = "Hello, World!";
if (preg_match($pattern, $string)) {
echo "Match found!";
} else {
echo "No match found.";
}
?>
Output:
Match found!
Explanation: This example demonstrates how to use preg_match()
to check if a string starts with "Hello".
Example of Using preg_replace()
<?php
$pattern = "/World/";
$replacement = "PHP";
$string = "Hello, World!";
$new_string = preg_replace($pattern, $replacement, $string);
echo $new_string;
?>
Output:
Hello, PHP!
Explanation: This example demonstrates how to use preg_replace()
to replace "World" with "PHP" in a string.
Example of Using preg_split()
<?php
$pattern = "/, /";
$string = "apple, orange, banana";
$fruits = preg_split($pattern, $string);
print_r($fruits);
?>
Output:
Array
(
[0] => apple
[1] => orange
[2] => banana
)
Explanation: This example demonstrates how to use preg_split()
to split a string into an array using a comma as the delimiter.