What is the purpose of using regex and if statements in PHP code?

Using regex and if statements in PHP code allows for the validation and manipulation of strings based on specific patterns or conditions. Regex (regular expressions) help to match and extract specific parts of a string based on a defined pattern, while if statements allow for conditional logic to be applied to control the flow of the program based on certain conditions. Together, they provide a powerful toolset for handling and processing string data in PHP.

// Example: Using regex and if statements to validate an email address

$email = "example@example.com";

if (preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)) {
    echo "Email address is valid.";
} else {
    echo "Email address is not valid.";
}