Regular expression for validating string and int in php

Asked

Viewed 79 times

-3

I need to validate this string.

$scop = "ES-1236"; fixed value access key ES- dynamic 1236 the dynamic being only integer numbers.

to validate I am creating a variable with the search $lets = "ES-";

and the expression to validate

if(preg_match("/{$lets}/i", $let)) {
echo true;
}

but in this format he is accepting to pass only ES- but I would like him to force a whole number after the ES-

  • 1

    For the purposes of knowledge. As ES- is not dynamic, you could also use https://www.php.net/manual/en/function.strtok.php. and test if the result is a number

2 answers

3

if(preg_match('/^(ES)-(\d){4}$/', $let)) 

This requires, in addition to initializing with ES, to be followed by - and end in 4 digits

2


Hello

You need an ER that contains the static part and the variable:

In your case 'ES-' is the static part and the digits are variable. Since you need an integer after the '-', then use the ' d' to identify numeric symbols (0,1,2, ...,8,9) and the modifier '+' so that at least one of these appears.

$scop = "ES-1236";
if(preg_match("/ES-\d+/", $scop)){
    echo "valido";
}else{
    echo "invalido";
}

You can run this code here:

Here you have a tester of this ER, with some valid and invalid strings.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.