准备价格WP和PHP都内置了一些东西。真正棘手的是要考虑所有可能的用户行为。您不会捕获所有内容,但您可以捕获很多内容,如无意中出现的空格、货币符号等。下面的功能有很好的注释,将向您展示我认为如何改善用户体验。我假设您的用户将使用与CMS中设置的语言相似的语言。
/**
* Convert a number to a price, formatted according to the blogs
* currency (which is the value returned by the WPLANG constant)
*
* @param unknown_type $price
* @return integer $price
*/
function wpse73492_validate_price( $price )
{
global $wp_locale;
// Avoid wrong user input: The decimals can only be an integer, no float or string
$decimals = absint( $decimals );
// Users might add leading/trailing white space:
$price = trim( $price );
// Users might use a lot of funky things in the search
// Example "shoes 10000" - they simply don\'t know better
// But: We allow a decimal point and the thousands separator
$regex = sprintf(
"0-9"
,$wp_locale->number_format[\'decimal_point\']
,$wp_locale->number_format[\'thousands_sep\']
);
preg_replace( "/[^{$regex}]/i", "", $string );
// Lets convert it to a "money unit"
// A "money unit" is something extremely different in a lot of contries.
// Let\'s take that behavior into account
// First we need to set the local and the charset: "en_EN.UTF-8"
setlocale(
LC_MONETARY
,sprintf(
\'%s.%s\'
,get_locale()
,get_bloginfo( \'charset\' )
);
// Second, we need to convert it to local currency
// The WP function is a wrapper for the PHP fn `number_format()`
// The 2nd argument defines the number of decimals, which should be 0
// This cares about removing every part that is no absolute integer, but a float.
$price = number_format_i18n( $price, 0 );
// Now we need some more funkieness:
// The DB isn\'t Babylon. Chinese and such is of our way
// Remove the thousands separator
$price = str_replace( $wp_locale->number_format[\'thousands_sep\'], \'\', $price );
// Last, we help the DB, and talk to it English
// This means that we need to get rid of ALOT: Everything non-numeric
preg_replace( "/[^0-9]/i", "", $string );
// Just to be sure, we then go and make it an absolute integer
return absint( $price );
}
然后只需对所有需要的值运行该函数。
// Call it like this:
wpse73492_validate_price( $_GET[\'pr_max\'] );
// Or: If you\'re sure you got nothing than prices from $_GET
// (Hint: If you got other stuff, you can extract it up front)
$prices = array_map( \'wpse73492_validate_price\', $_GET );