如何仅为方程中的操作数验证有效输入

时间:2013-03-15 15:25:59

标签: php

伙计们如何在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);

    }


    }
?>

2 个答案:

答案 0 :(得分: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
                )

        )

)

答案 1 :(得分:0)

您可以使用Drupal Form Api模块

来利用正则表达式规则
$form['firstoperand'] = array(
    '#rules' => 'regexp[/^((\+|\-)?[1-9]\d*(\.\d+)?)|((\+|\-)?0?\.\d+)$/]'
    '#filters' => 'trim'
    );