使用 php 获取 intval() ?
假设我有以下字符串:
danger13 afno 1 900004
使用 intval()
它给了我 13,但是,我想获取字符串中的最大整数,即 9000004,我怎样才能实现这一点?
编辑:字符串有不同的形式,我不知道最大的数字在哪里。
let's say I have the following string:
danger13 afno 1 900004
using intval()
it gives me 13, however, I want to grab the highest integer in the string, which is 9000004, how can I achieve this?
Edit: the string comes in different forms, and I don't know where the highest number will be.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要从字符串中取出所有整数,然后找到最大的...
$max
现在是900004
。请注意,这非常简单。如果您的字符串中有任何与模式
\d+
(1 个或多个数字)匹配的内容,但您不想将其作为单独的整数进行匹配(例如43.535
将返回535
),这不会让您满意。您需要更仔细地定义您的意思。You'll need to get all the integers out of the string, then find the biggest...
$max
is now900004
.Note that this is very simple. If your string has anything that matches the pattern
\d+
(1 or more digits) that you don't want to match as a separate integer (e.g.43.535
would return535
), this won't be satisfactory for you. You'll need to define more closely what you mean.对于字符串中按字典顺序排列的最高整数值(最多
PHP_INT_MAX
),您可以将数字分开并获取最大值:演示。
或者更好的自我记录:
For the lexicographical highest integer value within the string (up to
PHP_INT_MAX
) you can just split the numbers apart and get the maximum value:Demo.
Or better self-documenting:
ETA:更新为允许以数字结尾或包含数字的“单词”(感谢戈登!)
ETA: updated to allow for "words" that end in or contain numbers (Thanks Gordon!)