<span class="hljs-meta"><?php
// This article explains how to use PHP's preg_match function to validate phone number formats.
// We provide a detailed regex breakdown and practical examples to help you understand and apply it.
// --------------------------------------------------------------
<p>?></p>
<h1>Using preg_match Function to Validate Phone Number Format: Detailed Regex Patterns and Examples</h1>
<p>In web development, scenarios such as user registration and information entry often require validating phone number formats. PHP provides the <strong>preg_match</strong> function combined with <strong>regular expressions</strong> to accomplish this. This article will detail how to use preg_match to validate Mainland China's phone number format.</p>
<h2>1. Introduction to preg_match Function</h2>
<p>preg_match is a PHP function for regular expression matching, with the following syntax:</p>
<pre><code><span class="hljs-keyword">int preg_match(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0)
Where:
Mainland China phone numbers are usually 11 digits, starting with 1, and the second digit is typically between 3 and 9. The specific rules are:
Based on these rules, the regex can be written as follows:
<span class="fun">/^</span><span><span>1</span></span><span>[</span><span><span>3</span></span><span>-</span><span><span>9</span></span><span>]\d{</span><span><span>9</span></span><span>}$/</span>
<?php
function isValidPhoneNumber($number) {
return preg_match('/^1[3-9]\d{9}$/', $number) === 1;
}
// Examples:
$numbers = [
'13812345678', // Valid
'19900000000', // Valid
'12812345678', // Invalid (second digit not 3-9)
'1391234567', // Invalid (too short)
'139123456789' // Invalid (too long)
];
foreach ($numbers as $num) {
if (isValidPhoneNumber($num)) {
echo "$num is a valid phone number\n";
} else {
echo "$num is an invalid phone number\n";
}
}
?>
Using preg_match with an appropriate regex pattern efficiently validates phone number formats. For typical projects, this method is simple, fast, and accurate, effectively preventing invalid phone numbers from entering the system.
Of course, for more complex validation needs (such as including carrier-specific prefixes or international numbers), you can further optimize the regex or use dedicated number libraries for validation.