简体   繁体   中英

Check if string does not have 6 digit number

I'm trying to check if a string does not have any 6 digit number.

$myString = "https://www.website.net/sometext/123456/";

if ( preg_match( '/([^0-9]{6})/', $myString ) ) {
    echo 'If'; 
} else {
    echo 'Else';
}

The code above echos if which it should be false. I am not sure what I am missing.

This what I'm trying to achieve:

"https://www.website.net/sometext/123456/" -> false
"https://www.website.net/sometext/"        -> true
"https://www.website.net/"                 -> true

Either check whether the result of the preg_match is 0, while using \\d{6} :

if ( preg_match( '/\d{6}/', $myString ) === 0) {
    echo 'If'; 
} else {
    echo 'Else';
}

Or, if you wanted the preg_match to return 1 if the string doesn't contain any such number, repeat each character from the start to the end of the string while using negative lookahead for 6 characters:

if ( preg_match( '/^(?:.(?!\d{6}))+$/', $myString )) {
    echo 'If'; 
} else {
    echo 'Else';
}

Also note that [^0-9] means "anything but a digit" - but, that can be matched just with the \\D metacharacter instead. (similarly, to match a digit, or [0-9] , use \\d - don't use the character sets)

Instead of trying to say "not this" in regex, express that in PHP:

if ( preg_match( '/([0-9]{6})/', $myString ) !== 1) {
    echo 'If'; 
} else {
    echo 'Else';
}

Your current regex /([^0-9]{6})/ means "6 non-digit characters", not "does not contain 6 digits".

if (preg_match('/[0-9]\d{5}/',$myString)) {
    echo 'If';
}else{
    echo 'else';
}

Your expression matches any string with 6 consecutive non-digit chars. You need to match string with 6 digits then inverse the result:

if ( ! preg_match('/([0-9]{6})/', $myString)) {
    ...
}

You may match a 6 digit number with (?<!\\d)\\d{6}(?!\\d) pattern.

You may use it in a preg_match call and negate the result:

if (!preg_match('~(?<!\d)\d{6}(?!\d)~', "text1234567 more text")) { 
    echo "Does not contain a 6 digit number"; 
}

Or, you may add it to the negative lookahead and use preg_match without negation:

if (preg_match('~^(?!.*(?<!\d)\d{6}(?!\d))~s', "text1234567 more text")) { 
    echo "Does not contain a 6 digit number"; 
}

See the PHP demo .

Pattern details

  • ^ - start of string
  • (?!.*(?<!\\d)\\d{6}(?!\\d)) - a negative lookahead that fails the match if there is a match of
    • .* - any 0+ chars as many as possible ( s modifier makes . match any char)
    • (?<!\\d)\\d{6}(?!\\d) - 6 digits that are neither preceded nor followed with a digit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM