php 子字符串正则表达式
我一整天都在阅读 php 代码,但我似乎找不到我认为是一个简单问题的答案。
我有一个充满字符串的数组,我想看看字符串中的第一个字符是否是数字,然后用它做一些事情,例如:
if substr($stringArray[$i],0,1) == regexsomething[0-9]) { do stuff }
我都错了吗?
当然,我可以将正则表达式设置为 [^0-9] 以在开始时进行匹配,但 PHP preg_match 让我非常困惑。
任何建议都会很棒。
谢谢
I've been reading php code all day and what I can't seem to find an answer to what I believe is a simple question.
I've got an array full of strings and I want to see if the first character in a string is a number, then do something with it, e.g:
if substr($stringArray[$i],0,1) == regexsomething[0-9]) { do stuff }
Have I got this all wrong?
Surely I could set the regex to be [^0-9] to match at the start but the PHP preg_match is confusing me greatly.
Any advice would be super.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在方括号之外,
^
表示“开始”,但在[
之后,表示“反转整个类”。/[^0-9]/
将匹配任何包含非数字的内容。匹配单个数字的正则表达式是:PHP 已经有一个用于此目的的函数:
is_numeric()
如果您想走正则表达式路线,则不需要获取第一个字符。匹配以数字开头的任何内容的正则表达式为:
Outside brackets,
^
means "start", but right after a[
, it means "invert this whole class"./[^0-9]/
would match anything that contains a non-digit. A regular expression to match a single digit would be:PHP already has a function for this, though:
is_numeric()
If you want to go the regex route, you won't need to get the first character. A regex that matches anything that starts with a digit would be:
如果您想确保字符串是数字,您可以使用
is_numeric
,如下所示:如果您想确保它是单个数字,例如
7
您可以使用 < code>< 小于运算符If you wnat to make sure that a string is a number you can use
is_numeric
like so:If you want to make sure its a single digit like
7
you can use the<
less-than operator