What are some common uses of regular expressions in PHP for extracting specific content from strings?
Regular expressions in PHP are commonly used for extracting specific content from strings, such as extracting email addresses, phone numbers, URLs, or any other pattern within a larger text. By using regular expressions, you can define a pattern to search for within a string and extract the desired content. This can be useful for tasks like data validation, text parsing, or extracting information from unstructured text.
// Example: Extracting email addresses from a string
$string = "Contact us at email@example.com or visit our website at www.example.com";
$pattern = '/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/';
preg_match_all($pattern, $string, $matches);
$email_addresses = $matches[0];
// Output the extracted email addresses
foreach ($email_addresses as $email) {
echo $email . "\n";
}