Regular Expression in PHP Language
Regular expressions, often referred to as “regex” or “regexp,” are a powerful tool for pattern matching and text manipulation in
Regular expressions, often referred to as “regex” or “regexp,” are a powerful tool for pattern matching and text manipulation in
A regular expression is a sequence of characters that forms a search pattern. It can be used for various purposes, such as:
Regular expressions in PHP are often used with functions like preg_match()
, preg_match_all()
, and preg_replace()
.
To match a specific character, you simply include that character in the regular expression.
Example:
$pattern = "/a/"; // This pattern matches the character 'a'
$text = "apple";
if (preg_match($pattern, $text)) {
echo "Match found!";
} else {
echo "No match found.";
}
Square brackets []
are used to specify a set of characters to match.
Example:
$pattern = "/[aeiou]/"; // This pattern matches any vowel
$text = "apple";
if (preg_match($pattern, $text)) {
echo "Vowel found!";
} else {
echo "No vowel found.";
}
Quantifiers specify how many times a character or group of characters should appear.
*
matches zero or more occurrences.+
matches one or more occurrences.?
matches zero or one occurrence.{n}
matches exactly n occurrences.{n,}
matches n or more occurrences.{n,m}
matches between n and m occurrences.Example:
$pattern = "/\d+/"; // This pattern matches one or more digits
$text = "Age: 30";
if (preg_match($pattern, $text, $matches)) {
echo "Age: " . $matches[0];
}
Anchors are used to specify the position of a pattern within the text.
^
matches the start of a line.$
matches the end of a line.Example:
$pattern = "/^Hello/"; // This pattern matches lines starting with "Hello"
$text = "Hello, World!";
if (preg_match($pattern, $text)) {
echo "Line starts with 'Hello'.";
}
$pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/";
$email = "example@email.com";
if (preg_match($pattern, $email)) {
echo "Valid email address.";
} else {
echo "Invalid email address.";
}
$pattern = "/https?:\/\/[^\s]+/";
$text = "Visit my website at https://example.com or http://testsite.net";
if (preg_match_all($pattern, $text, $matches)) {
foreach ($matches[0] as $url) {
echo "URL: $url<br>";
}
}
Subscribe to get the latest posts sent to your email.