What is the purpose of using preg_match in PHP for validating input in a textarea?

When validating input in a textarea in PHP, using preg_match allows you to check if the input matches a specific pattern or regular expression. This can help ensure that the input meets certain criteria, such as only allowing certain characters or formats. By using preg_match, you can validate the input before processing it further, helping to prevent potential security vulnerabilities or errors in your application.

// Validate input in a textarea using preg_match
$textarea_input = $_POST['textarea_input'];

// Define a regular expression pattern to allow only alphanumeric characters and spaces
$pattern = '/^[a-zA-Z0-9\s]+$/';

// Check if the input matches the pattern
if (preg_match($pattern, $textarea_input)) {
    // Input is valid, proceed with processing
    echo "Input is valid!";
} else {
    // Input is not valid, display an error message
    echo "Invalid input. Only alphanumeric characters and spaces are allowed.";
}