[英]Need help in string parsing?
我正在根據用戶輸入創建 SQL 查詢:
// user input
$amount = '20';
// query in zend
$select->where('amount = ?', $amount );
現在根據新的要求,用戶也可以輸入以下格式:
$amount = '20';
$amount = '<20';
$amount = '<=20';
$amount = '>20';
$amount = '>=20';
$amount = '=20';
我認為您了解新功能。 那么如何解析$amount
變量以適應上述查詢呢? 我必須將number
和sign
與$amount
變量分開,才能在其正確的 position 上使用它們。 如果符號錯誤(ie $amount='$%20'; )
,則應將其視為等號(ie $amount='=20'; )
我應該遵循什么方法來解決這個問題?
謝謝
您可以使用以下正則表達式來分隔它們:
preg_match('/(<|>|=|<=|>=)([0-9]+)/', $amount, $matches);
$sign=$matches[1];
$number=$matches[2];
更新:我對此進行了測試,發現它不能正確處理錯誤的標志。 我想出了以下似乎工作正常的代碼:
$amount=">=20";
preg_match('/([^0-9]*)([0-9]+)/', $amount, $matches);
$sign=preg_match('/^(>|<|=|<=|>=)$/', $matches[1]) ? $matches[1] : '=';
$number=$matches[2];
如果給定的字符串>=20
那么符號是>=
並且數字是 '20',如果給定的字符串是 '%$20' 那么符號是=
並且數字是20
。
$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 );
}
如果用戶可以指定帶有值的運算符,則必須小心。 嘗試:
$input = '<=20';
$allowedOperators = array('<', '<=', '>', '>=', '=');
if ( in_array(substr($input,0,2), $allowedOperators) ) {
$operator = substr($input,0,2);
} else if ( in_array(substr($input,0,1), $allowedOperators) ) {
$operator = substr($input,0,1);
} else {
$operator = '=';
}
$amount = (int) substr($input, strlen($operator));
$select->where('amount ' . $operator . ' ?', $amount );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.