How can URLs be prevented from being submitted in PHP contact forms to avoid spam?

To prevent URLs from being submitted in PHP contact forms to avoid spam, you can add a validation check to the form submission code. This validation check can include checking if the input contains any URLs and rejecting the form submission if it does.

// Check if the form submission contains any URLs
if (preg_match('/\b(?:https?|ftp):\/\/|www\./i', $_POST['message'])) {
    // Redirect back to the form with an error message
    header("Location: contact_form.php?error=url_detected");
    exit();
} else {
    // Process the form submission
    // Your code to handle the form submission goes here
}