dongpenggan6812 2011-08-01 01:54
浏览 35
已采纳

自由的货币政策

I'm working on a PHP application. I need to validate that a string is useable as a currency value. I would like the following to validate:

$5.00  
5  
5.00   
£5.00  

I want the pattern to be liberal enough to accept a reasonable string. I would also like it to accept an currency symbol; however, to validate currency, it can be any character or characters because I'll ultimately store the value as a two decimal float. So, '$5.00' or 'USD 5.00' would become '5.00' when stored in the database. I'm currently using the following:

preg_match('/^[0-9]*\.?[0-9]+$/',$value)

It works for "5" or "5.00", but it does not account for the currency symbol. How do I adjust this to allow for the currency symbol?

Thank you!

EDIT: According to a comment below, it looks like my regex will allow too many decimals. Can you also help me sort out that issue?

  • 写回答

2条回答 默认 最新

  • dongwuli5105 2011-08-01 01:57
    关注

    To allow all currency symbols you will need to use Unicode Character Properties

    \p{Sc} or \p{Currency_Symbol}: any currency sign.

    Try with this one:

    $value=preg_replace('/^(\p{Sc}?\d*)((\.|,)\d\d\d)?\d*$/u','$1$2',$value);
    

    But if you are expecting the number from an input, will be better make a form where the user specify the currency from a selectable list, and just take care whether the user will only introduce numbers, that's how PAYPAL does.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?