Arrays and variables, allow only certain characters, check all strings

I have an HTML form. When filled out I have four strings. I want to check the strings for:

  1. only digits and commas are permitted in the string - I’m guessing I’d use preg_match here

  2. if the last item is a comma then strip that comma off. I’m currently using a check like this, is it the most efficient way?


$FormFieldOne = "7,8,";
if (strripos($FormFieldOne,",") == strlen($FormFieldOne)-1) {
  // last character is a hanging comma, strip it off
  $FormFieldOne = substr($FormFieldOne, 0, -1);
}

  1. If step 2 is efficient and I wanted to do this with all four form fields, I’m assuming I could assign them to an array and use each/foreach to step through but how do I refer to the variable name $FormFieldOne correctly?

$myarray = array($FormFieldOne, $FormFieldTwo, $FormFieldThree, $FormFieldFour)

I know I can reference $myarray[0] to get the contents of $FormFieldOne but how do I refer to the variable $FormFieldOne so I can use substr to strip off that last character?

try

 
foreach($myArray as $value) {
 
/*
Use your IF block code in 1) but substitute 
$value for $FormFieldOne
*/
 
}

I ended up with this:


$formvariables = array($one, $two, $three, $four);

while (list($key, $val) = each($formvariables)) {

  if (strlen($val) > 1) {
    if (strripos($val,",") == strlen($val)-1) {
      $val = substr($val, 0, -1); 
    }
  }
  echo "<br />" . $val;
}

Pretty much the same ? The check for length was so strings that only had one value (thus no comma) weren’t edited.

another option, combine the 2 IF’s into 1 IF

 
foreach($myArray as $value)
    if (strripos($value,",") == strlen($value)-1 || strlen($value > 1)) {
          $value = substr($value, 0, -1);
    }
    echo "<br />" . $value;
}


$vars = array(
  '012,3 abc #,' 
, 'ff012 +,3 bbb,'
);


function digitsCommasOnly( $input ){
// rm all but Numbers and commas
$input = '012,3 abc #,';
$output = preg_replace('#[^0-9,]#', '', $input);

// then get rid of optional trailing comma
return rtrim( $output, ",");
}

$clean = array_map("digitsCommasOnly", $vars);

var_dump($clean);

// gives:
// 0123,3
// 0123,3