ctype_digit只允许以4开头的10位数字

时间:2013-07-31 08:40:18

标签: php

我使用以下功能只允许数字。

if (empty($VAT) || (!(ctype_digit($VAT)))) {
    $mistakes[] = 'ERROR - Your title is either empty or should only contain NUMBERS starting with a 4.';

有没有办法可以添加/修改此功能只接受10位数字,它必须以数字4开头?

4 个答案:

答案 0 :(得分:1)

你正在寻找

preg_match()

<?php
header('Content-Type: text/plain; charset=utf-8');

$number1 = '4123456789';
$number2 = '3123456789';

$regex = '/^4\d{9}$/';
// ^ test pattern: 4 in begining, at least 9 digits following.

echo $number1, ': ', preg_match($regex, $number1), PHP_EOL;
echo $number2, ': ', preg_match($regex, $number2), PHP_EOL;
?>

输出:

4123456789: 1
3123456789: 0

更新了来源:

if (!preg_match('/^4\d{9}$/', $VAT)) {
    $mistakes[] = 'ERROR - Your title is either empty or should only contain NUMBERS starting with a 4.';
}

对于可变位数,请使用以下正则表达式:'/^4\d{1,9}$/'

答案 1 :(得分:1)

你可以使用正则表达式:

if(preg_match('/^4\d{9}$/', $VAT) == 0){
   $mistakes[] = 'ERROR - Your title is either empty or should only contain NUMBERS starting with a 4.';
}

如果你需要匹配任何其他字符串或数字模式,这是一个你可以测试你的正则表达式的网站:regexpal.com它有指针和教程以及一切可以帮助你学习如何匹配字符串模式并测试你自己的正则表达式

答案 2 :(得分:1)

使用preg_match并返回匹配或布尔

preg_match('/^[4]{1}[0-9]{9}$/', $VAT, $matches);

替代使用:

$VAT = "4850999999";

if (preg_match('/^[4]{1}[0-9]{9}$/', $VAT))
    echo "Valid";
else
    echo "Invalid";

平均值

^[4]从数字4(四)开始

{1}初始数量限制

[0-9]允许的字符

{9}第一个号码后需要9个单位数

答案 3 :(得分:0)

也许不是最好的方法,但使用REGEX就可以做到。

这是一种方式

preg_match('/4[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]/', $string, $matches);

其中$ string是您要检查的字符串,$ matches是保存一致结果的地方。