Le espressioni regolari permettono di cercare e manipolare pattern nei testi.
preg_match
// Verifica pattern
if (preg_match("/^[a-z]+$/i", $input)) {
echo "Solo lettere";
}
// Estrai matches
preg_match("/(d{2})/(d{2})/(d{4})/", "15/01/2024", $matches);
// $matches = ["15/01/2024", "15", "01", "2024"]preg_match_all
$text = "Email: test@mail.com e info@site.it";
preg_match_all("/[w.-]+@[w.-]+/", $text, $emails);preg_replace
// Rimuovi spazi multipli
$clean = preg_replace("/s+/", " ", $text);
// Censura parole
$text = preg_replace("/badword/i", "***", $text);Pattern comuni
- Email:
/^[w.-]+@[w.-]+.[a-z]{2,}$/i - Telefono IT:
/^(+39)?s?d{3}[s.-]?d{6,7}$/