PHP › Regular Expressions in PHP
What is a regular expression, and how do you use PHP's preg_match function to check whether a string matches a specific pattern?
BeginnerAnswer
A regular expression is a specialized pattern used to describe and match specific sequences of characters within text, and PHP's preg_match function checks whether a given string contains a match for a specified regular expression pattern, returning one if a match was found and zero if it was not, making it a common tool for validating input formats, such as confirming a string looks like a valid phone number.
if (preg_match('/^[0-9]{3}-[0-9]{4}$/', $phoneNumber)) {
echo 'Valid format';
}Real-world example A form validation function uses preg_match to confirm a submitted phone number follows the expected three digit dash four digit pattern before accepting the submission.