Current Location: Home> Latest Articles> Combined with filter_var to implement regular replacement of email or URL

Combined with filter_var to implement regular replacement of email or URL

M66 2025-05-14

In PHP, the filter_var function is a very useful tool for filtering and verifying data. It supports multiple filters, which can help us quickly verify the validity of data such as email addresses, URLs, etc. We can perform some replacement operations in combination with regular expressions to modify the email address or URL.

Verify and replace URLs with filter_var

When we need to process the URL and make sure it conforms to a specific format, the filter_var function can be very convenient for us to verify that the URL is valid. In addition, combined with regular expressions, we can also use this function when replacing the domain name or path of the URL.

Sample code:

 <?php
// original URL
$url = "https://www.example.com/path/to/page";

// verify URL Is it valid or not
if (filter_var($url, FILTER_VALIDATE_URL)) {
    // if URL efficient,Replace domain name
    $new_url = preg_replace('/https?:\/\/(www\.)?example\.com/', 'https://m66.net', $url);
    echo "Replaced URL: " . $new_url;
} else {
    echo "Invalid URL";
}
?>

Code description:

  • filter_var($url, FILTER_VALIDATE_URL) is used to verify whether the URL is valid.

  • preg_replace is used to replace the domain name part in the URL. We use the regular expression '/https?:\/\/(www\.)?example\.com/' to match the example.com domain name and replace it with m66.net .

Output:

 Replaced URL: https://m66.net/path/to/page

Verify and replace email addresses using filter_var

The filter_var function can also be used to verify the validity of an email address. We can combine regular expressions to modify the domain name part of the email address to complete the processing of the email address.

Sample code:

 <?php
// original邮件地址
$email = "user@example.com";

// verify邮件地址Is it valid or not
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // if邮件地址efficient,Replace domain name
    $new_email = preg_replace('/@example\.com$/', '@m66.net', $email);
    echo "Replaced邮件地址: " . $new_email;
} else {
    echo "Invalid邮件地址";
}
?>

Code description:

  • filter_var($email, FILTER_VALIDATE_EMAIL) is used to verify the validity of the email address.

  • preg_replace is used to replace the domain name part in the email address. We use the regular expression '/@example\.com$/' to match @example.com and replace it with @m66.net .

Output: