Skip to content
PHP Logo

How can PHP developers extract specific content from a string using regular expressions?

To extract specific content from a string using regular expressions in PHP, developers can use the preg_match() function. This function allows developers to search for a specific pattern within a string and extract the matching content. By defining a regular expression pattern that matches the desired content, developers can extract the specific information they need from a given string.

php
$string = "Hello, my email is example@email.com";
$pattern = '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/';
preg_match($pattern, $string, $matches);
$email = $matches[0];

echo $email; // Output: example@email.com