在php中格式化数据
我需要做的是格式化变量中的数据,如下所示:
format: xxx-xxx variable: 123456 output: 123-456
问题是我需要能够更改格式,因此静态解决方案不起作用。 我也希望能够更改变量大小,例如:
format: xxx-xxx variable: 1234 output: 1-234
注意:所有变量都是数字
编辑 我应该清楚格式,它不会总是以 3 分组,并且它可能有比“-”更多的符号,组将不稳定 1-22-333-4444 它只会按 1-5 分组
What I need to be able do is format data in a variable, like so:
format: xxx-xxx variable: 123456 output: 123-456
The problem is I need to be able to change the format, so a static solution wouldn't work. I also like to be able to change the variable size, like:
format: xxx-xxx variable: 1234 output: 1-234
Note: All of the variables will be numbers
Edit I should have been clear on the format its not going to always be grouping of 3, and it may have more then "-" as a symbol, the groups will be inconstant 1-22-333-4444 it will only be in grouping of 1-5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最好的选择是 preg_replace。
正则表达式需要一些时间来适应,但这可能是您最好的选择...
编辑:
关键是使除了最右边的一组之外的每组都非贪婪,从而允许右-面向侧面的模式匹配。
Your best bet is preg_replace.
Regular expressions take some getting used to, but this is probably your best bet...
EDIT:
The key is to make every set, except the righ-most one non-greedy, allowing for a right-side oriented pattern match.
如果您要格式化的输入始终是整数,您可以尝试 number_format 并将格式设置为金钱(千等..)
这是一个解决方案,它可以接受任何字符串并将其转换为您想要的格式:
If the input you are formatting is always an integer you can try number_format and format as money (thousands etc..)
Here is a solution which takes any string and turns it into your desired format:
您可以实现策略模式,并拥有可在运行时交换的新格式化类。 如果您以前没有见过它,它看起来很复杂,但它确实有助于提高可维护性,并允许您随时使用 setFormatter() 切换格式化程序。
然后你就会有你的格式化类,如下所示:
然后你可以像这样使用它:
You could implement the strategy pattern and and have new formatting classes that are swappable at run time. It looks complicated if you haven't seen it before but it really helps with maintainability and allows you to switch the formatter with the setFormatter() at any time.
Then you would have your formatting class which would be like so:
Then you could use it like this: