0

伙计们,我如何验证 php 中的操作数输入?我正在创建一个非常简单的计算器页面.. 所以 '+' '-' 和 '.' 除了数字之外,它们也是有效的输入。所以 is_numeric 是不够的验证。另外,如果你们知道在 drupal 中实现此验证的方法,请随时发布。顺便说一句,我正在使用 drupal。顺便说一下,这是我的 drupal 代码。我创建了一个简单的计算器模块。

<?php
/**
 * Implements hook_menu()
  */

function calculator_menu(){
    $items['calculator-page'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('calculator_form'),
    'access callback' => TRUE,

    );
    return $items;
    }



function calculator_form(){

    $form['firstoperand'] = array(
    '#title' => t('First operand'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#rules' => 'numeric'
    );

    $form['operator'] = array(
    '#type' => 'select',
    '#options' => array(
        '+' => t('Plus'),
        '-' => t('Minus'),
        '*' => t('Times'),
        '/' => t('Divided by'),
    ),
    '#required' => TRUE,
    );


    $form['secondoperand'] = array(
    '#title' => t('Second operand'),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#rules' => 'numeric'
    );

    $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Generate',
    );

    $form['#submit'][] = 'calculator_form_submit';

    return $form;


    }

function calculator_form_submit($form, &$form_state){

    $firstoperand=$form_state['values']['firstoperand'];
    $operator=$form_state['values']['operator'];
    $secondoperand=$form_state['values']['secondoperand'];

    if(!is_numeric($firstoperand) || !is_numeric($secondoperand)){
        drupal_set_message("Must use numbers");
    }
    else{

    /*if($operator=='+'){

    $result= $firstoperand+$secondoperand;
    }
    if($operator=='-'){

    $result= $firstoperand-$secondoperand;
    }
    if($operator=='*'){

    $result= $firstoperand*$secondoperand;
    }
    if($operator=='/'){

    $result= $firstoperand/$secondoperand;
    }*/

    $result = $firstoperand+$operator+$secondoperand;




    drupal_set_message($result);

    }


    }
?>
4

2 回答 2

2

我会考虑使用 preg_match 来查找这些符号的正则表达式模式匹配。例如:

  1 <?php
  2 $subject = "1.00+2x3/4";
  3 $pattern = '/\.|\+|x|\//';
  4 preg_match_all($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
  5 print_r($matches);
  6 ?>

这将产生以下结果:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => .
                    [1] => 1
                )

            [1] => Array
                (
                    [0] => +
                    [1] => 4
                )

            [2] => Array
                (
                    [0] => x
                    [1] => 6
                )

            [3] => Array
                (
                    [0] => /
                    [1] => 8
                )

        )

)
于 2013-03-15T15:32:58.470 回答
0

您可以通过使用Drupal Form Api模块来利用正则表达式规则

$form['firstoperand'] = array(
    '#rules' => 'regexp[/^((\+|\-)?[1-9]\d*(\.\d+)?)|((\+|\-)?0?\.\d+)$/]'
    '#filters' => 'trim'
    );
于 2013-03-15T15:57:39.260 回答