Regular expressions are used to search, match, and replace patterns in strings. PHP supports regular expressions using functions like preg_match()
, preg_replace()
, and preg_split()
.
To check if a pattern matches a string, use preg_match()
:
<?php
$pattern = "/\d+/"; // Pattern to match digits
$string = "Hello 123";
if (preg_match($pattern, $string)) {
echo "Match found!";
} else {
echo "No match found.";
}
?>
To replace a pattern in a string, use preg_replace()
:
<?php
$pattern = "/\d+/";
$string = "Hello 123";
$replacement = "XYZ";
$newString = preg_replace($pattern, $replacement, $string);
echo $newString; // Output: Hello XYZ
?>
Write a regular expression to match a valid email address and use it to validate an email input from a form.
Answers: Use preg_match()
to match patterns. Use preg_replace()
to replace patterns.