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

Php ctype_digit仅允许以4开头的10位数字,php,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开头?也许不是最好的方法,但使用正则表达式可以做到这一点 这是一种方式 preg_match('

我使用以下函数只允许数字

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

是否有一种方法可以添加/修改此函数,使其仅接受10位数字,并且必须以数字4开头?

也许不是最好的方法,但使用正则表达式可以做到这一点

这是一种方式

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是保存一致结果的位置。

是您要查找的内容:

<?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;
?>
更新资料来源:

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}$/”。

您可以为此使用正则表达式:

if(preg_match('/^4\d{9}$/', $VAT) == 0){
   $mistakes[] = 'ERROR - Your title is either empty or should only contain NUMBERS starting with a 4.';
}
如果您需要匹配任何其他字符串或数字模式,这是一个您可以测试正则表达式的网站:它有指针、教程和所有帮助您学习如何匹配字符串模式和测试您自己的正则表达式的内容。

使用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个单位的数字

使用“否”,但您可以使用正则表达式或字符串匹配编写一个新函数。所有ctype_*函数所做的只是检查字符类型,而不是它们的实际值。然而,我想说的是,标题不是一个好名字,因为它应该包含一个10位数的vat号码。PS,忘记更改错误消息。标题应该是VAT编号。@Anigel ctype_uu函数不检查类型,而是检查值。在提出其他索赔之前,请查阅手册。声明它检查文本字符串中的数值,而不是参数类型-唯一允许的类型是文本。@eis也许你误解了我的意思,我没有说它采用了不同的变量类型。它检查字符串中的字符类型,如果这些字符的特定值大于40000或其他任意数字,则不检查给定的字符类型。非常感谢您提供的所有建议。我使用了preg_匹配。没问题,Alwina,检查我的编辑
$VAT = "4850999999";

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