What is the purpose of the regex function in PHP and how can it be used to manipulate text content within variables?

The purpose of the regex function in PHP is to search, match, and manipulate text content within variables based on specific patterns or rules defined by regular expressions. This can be useful for tasks such as searching for specific words or patterns, replacing text, extracting data, and validating input.

// Example: Using regex to extract all email addresses from a string
$text = "Contact us at email1@example.com or email2@example.com for inquiries.";

preg_match_all("/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/", $text, $matches);

foreach ($matches[0] as $email) {
    echo $email . "\n";
}