PHP正则表达式最小和最大长度不能按预期工作


php regular expression minimum and maximum length doesn't work as expected

我想在PHP中创建一个正则表达式,它将允许用户以以下任意一种格式输入电话号码。

345 - 234

898

234 - 898

345

235-123-456

548 812 346

number的最小长度为7,最大长度为12。

问题在于,正则表达式并不关心最小和最大长度。我不知道有什么问题。请帮我解决这个问题。下面是正则表达式

if (preg_match("/^([0-9]+(('s?|-?)[0-9]+)*){7,12}$/", $string)) {
echo "ok";
} else {
echo "not ok";
}

谢谢你阅读我的问题。我将等待回复

你应该在你的模式上使用开始(^)和结束($)符号

$subject = "123456789";
    $pattern = '/^[0-9]{7,9}$/i';
    if(preg_match($pattern, $subject)){
        echo 'matched';
    }else{
        echo 'not matched';
    }

您可以使用preg_replace去除非数字符号并检查结果字符串的长度。

$onlyDigits = preg_replace('/''D/', '', $string);
$length = strlen($onlyDigits);
if ($length < 7 OR $length > 12)
  echo "not ok";
else
  echo "ok";

只需这样做:

if (preg_match("/^'d{3}[ -]'d{3}[ -]'d{3}$/", $string)) {

这里'd表示0-9中的任意数字。[ -]表示空格或连字符

您可以在模式开始时使用前瞻性断言(?=...)检查长度:

/^(?=.{7,12}$)[0-9]+(?:['s-]?[0-9]+)*$/

分解您的原始正则表达式,它可以读成如下:

^                   # start of input
(
    [0-9]+          # any number, 1 or more times
    (
        ('s?|-?)    # a space, or a dash.. maybe
        [0-9]+      # any number, 1 or more times
    )*              # repeat group 0 or more times
)
{7,12}              # repeat full group 7 to 12 times
$                   # end of input

所以,基本上,你允许"任意数字,1次或更多次"后面跟着一组"任意数字1次或更多次,0次或更多次"重复"7到12次"——这有点破坏了你的长度检查。

你可以采取更严格的方法,写出每个单独的数字块:

(
    'd{3}         # any 3 numbers
    (?:[ ]+|-)?   # any (optional) spaces or a hyphen
    'd{3}         # any 3 numbers
    (?:[ ]+|-)?   # any (optional) spaces or a hyphen
    'd{3}         # any 3 numbers
)
简化:

if (preg_match('/^('d{3}(?:[ ]+|-)?'d{3}(?:[ ]+|-)?'d{3})$/', $string)) {

如果你想限制分隔符只有一个空格一个连字符,你可以更新正则表达式使用[ -]而不是(?:[ ]+|-);如果你希望这是"可选的"(即数字组之间不能有分隔符),请在每个数字组的末尾添加一个?

if (preg_match('/^('d{3}[ -]'d{3}[ -]'d{3})$/', $string)) {

希望它能帮到你。

Validator::extend('price', function ($attribute, $value, $args) {
return preg_match('/^'d{0,8}('.'d{1,2})?$/', $value);
});