使用 PHP 修剪字符串开头的任何零
用户将在字段中填写与其帐户相关的数字。不幸的是,一些用户会在号码开头添加零来组成六位数字(例如 000123、001234),而其他用户则不会(例如 123、1234)。我想“修剪”前面以零为前缀的用户的数字,因此如果用户输入 000123,它将删除零以变为 123。
我已经看过 trim 和 substr 但我不相信这些可以完成工作吗?
Users will be filling a field in with numbers relating to their account. Unfortunately, some users will have zeroes prefixed to the beginning of the number to make up a six digit number (e.g. 000123, 001234) and others won't (e.g. 123, 1234). I want to 'trim' the numbers from users that have been prefixed with zeros in front so if a user enters 000123, it will remove the zeroes to become 123.
I've had a look at trim and substr but I don't believe these will do the job?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用
ltrim()
并传递字符应作为第二个参数删除:ltrim
仅从字符串的开头(左侧) 删除指定的字符(默认空白)。You can use
ltrim()
and pass the characters that should be removed as second parameter:ltrim
only removes the specified characters (default white space) from the beginning (left side) of the string.应该完成这项工作,根据 PHP 手册
should do the job, according to the PHP Manual
您始终可以强制 PHP 将其解析为 int。如果需要,您可以稍后将其转换回字符串
You can always force PHP to parse this as an int. If you need to, you can convert it back to a string later
您可以通过从字符串转换为数字并再转换回来来删除前导零。例如:
You can drop the leading zeros by converting from a string to a number and back again. For example:
只需将您的数字乘以零即可。
Just multiply your number by zero.