check a string with php [closed]

-2

I have an input where the user informs several product codes, and the system returns a list.

But I need to validate the string or verify it is exactly like this: 132,234,14,56

That is, each code separated by a comma.

I tried to do this, but it did not work:

if (preg_match('/^,/', $ids)) {
       echo "erro nas informações";
    }

NOTE: It must always be integers, separated by, can not end with, can not contain letters and no space.

    
asked by anonymous 04.07.2016 / 16:30

3 answers

1

So I understand it is a list containing an indeterminate number of integers separated by commas. So, it would look like this:

if(preg_match("/^(\d+,)*\d+/",$ids)===false){
  echo "erro nas informações";
}
    
04.07.2016 / 17:32
0

One way is to compare the number of commas in the string and the amount of data that these commas separate, for example:

$string = "132,234,14,56";

if(substr_count($string,",") == (count(array_filter(explode(",",$string))) - 1)){
  echo "Valida";
} else {
  echo "Invalida";
}

In your example, you have three commas that separate four values, substr_count counts the quantity of commas, and compares with the amount of values by doing a explode in the string and then a array_filter to eliminate voids.

You can also validate values using a callback function in array_filter , eg:

$strings = array("132,234,14,56","132,234,14,56,ABC","132,234,14,56,",",132,234,14,56,ABC","1,2,3");

foreach ($strings as $string){

  if(substr_count($string,",") == (count(array_filter(explode(",",$string),'is_numeric')) - 1)){
    echo "String $string é válida";
  } else {
    echo "String $string é inválida";
  }
  echo PHP_EOL;
}

Ideone

    
04.07.2016 / 17:16
-2

Try the strpos .

if (strpos($mystring, ".") !== false) {
    //código
}
    
04.07.2016 / 16:36