phpstringparsingzend-framework

Parse string composed of an optional comparison operator followed by an integer


I am creating SQL query based on user input:

// user input
$amount = '20';

// query in zend 
$select->where('amount = ?', $amount );

Now according to new requirements user can input in following formats as well:

$amount = '20';
$amount = '<20';
$amount = '<=20';
$amount = '>20';
$amount = '>=20';
$amount = '=20';

I think you understand the new feature. So how can I parse $amount variable to fit it in above query? I have to separate number and sign from $amount variable to use them on their proper position. And if there is wrong sign(i.e $amount='$%20'; ) then it should consider it as equal sign(i.e $amount='=20'; )

What approach should I follow to solve this?

Thanks


Solution

  • $parts = array();
    if (preg_match('/^(\D+)?(\d+)$/', $amount, $parts)) {
        $operator = (!in_array($parts[1], array('=', '<', '<=', '>=', '>'))) ? '=' : $parts[1];
        $value    = $parts[2];
        $select->where('amount ' . $operator . ' ?', $value );
    }