Agaric Design Collective

Making sure multiple numeric ID input can be allowed in the most flexible way possible

By Benjamin Melançon
on 19 Mar
0 comments

Key words and phrases

php collapse whitespace string Drupal securely handle form input over-engineer allow multiple pubmed ids so i make sure they can be allowed in the most flexible way possible Check if a number is an integer php validate comma separated integers faster ereg or preg drupal check integer

Tags

Description

Agaric knows that the best usability would never have people entering numeric IDs into a text field in the first place, but pending fancy remote search and completion techniques, we can at least take a set of numbers without rejecting them for using semicolons instead of commas.

<?php
/**
* Replace all other separators in a string with spaces and split into arary.
*
* Agaric Utility function most practical for numeric IDs, rather than text.
*
* @param $string
*  String value containing one or more simple values, separated by anything.
* @return
*  Array of values from the split string.
*/
function biblioreference_au_rationalize_separators($string) {
 
// transform all separators into spaces
  // @REVIEW for pubmed ids we could replace all non-numeric with space
 
$seps = array(',', ';', ':', '|', '.');
 
$pmids = str_replace($seps, ' ', $form_state['values']['biblioreference_pubmed_id']);
 
$string = trim(ereg_replace(' +', ' ', $string));
  return
explode(' ', $string);
}
?>

Then checking that each of those is an actual integer is another step.

is_int is no good for checking form data, but there are a couple ways:

<?php
if (eregi("^[[:digit:]]+$", $presumed_integer_value) {
  return
FALSE;
}
?>

or:

<?php
if (preg_match("/[^0-9]/", $presumed_integer_value)) {
  return
FALSE;
}
?>

preg is usually faster, and apparently generally better.

Oh wait. There is a PHP function for checking that something is a straight-up integer, provided that it is given a string value (which forms always will). That function is

<?php
  ctype_digit
($presumed_integer_value)
?>

http://us2.php.net/manual/en/function.ctype-digit.php

 

Post new comment
The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote> <h1> <h2> <h3> <h4> <h5> <h6> <small> <pre> <strike> <sub> <sup> <kbd> <s>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.