Skip to content
PHP Logo

How can regular expressions (regex) be used in PHP to extract specific content from a string based on defined patterns or characters?

Regular expressions (regex) can be used in PHP to extract specific content from a string by defining patterns or characters to match. This is useful when you need to extract certain information, such as email addresses, phone numbers, or URLs, from a larger text. By using functions like preg_match() or preg_match_all(), you can search for and extract the desired content based on the defined regex pattern.

php
$string = "Hello, my email is example@email.com and my phone number is 123-456-7890.";
$pattern = '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/'; // regex pattern to match email addresses

if (preg_match($pattern, $string, $matches)) {
    echo "Email found: " . $matches[0];
} else {
    echo "Email not found.";
}