其他教程

其他教程

Products

当前位置:首页 > 其他教程 >

PHP正则表达式任何数字

GG网络技术分享 2025-03-18 16:15 2


问题描述:

I search for patterns like this number+space+number+space+anything

If have this right now:

if( preg_match( \'[0-9][ ][0-9][ ].\', $searchString ) )

This seems to work ok but fails on the numbers. As far as i can see there should be a selector for \"any number\". How can i do this in regex.

It should return true for these cases:

0 0 asdf

1 0 asdf

0 30 adsf asdf

22 0 a

...

图片转代码服务由CSDN问答提供

感谢您的意见,我们尽快改进~

功能建议

我搜索这样的模式+空格+数字+空格+任何东西</ p>

<n p>如果现在有这个:</ p>

  if(preg_match(\'[0-9] [] [0-9] []。\',$ searchString))

</ code> </ pre>

这似乎工作正常,但数字失败。 据我所知,应该有一个“任意数字”的选择器。 如何在正则表达式中执行此操作。</ p>

对于这些情况,它应该返回true:</ p>

  0 0 asdf 

1 0 asdf

0 30 adsf asdf

22 0 a

...

</ code> </ pre>

</ div>

网友观点:

[0-9] only accepts the integers 0,1,2,3,4,5,6,7,8,9. For any integer, you need to allow one or more repetitions of [0-9]. If you use the shortcut \\d for [0-9] then you can write it as

\\d+ \\d+ .*

The + symbol means One or more repetitions.

Note:

It seems like your new to reg expression. Try out this free regex tutorial.

I\'m kind of surprised that works seeing that you should have your regex between //. But that aside, you should realise that your [0-9] is only looking for a MANDATORY ONE INSTANCE of a digit.

Changing that to [0-9]+ should fix your issue, though I think studying a bit of regex first will help you in the long run.

Change your regexp pattern as shown below:

$re = \\\"/\\d+? \\d+? .*$/\\\";

var_dump(preg_match($re, \\\"0 30 adsf asdf\\\")); // 1

var_dump(preg_match($re, \\\"22 0 a\\\")); // 1

Details:

  • \\d+? - should match at least one number
  • .*$ - matches any character at the end of the string

PHP正则表达式核心技术完全详解 第7节 数组元素正则匹配

作者:极客小俊 一个专注于web技术的80后

我不用拼过聪明人,我只需要拼过那些懒人 我就一定会超越大部分人!

极客小俊@知乎,官方首发原创文章

博客: 极客小俊GeekerJun


PHP正则匹配数组中的元素

preg_grep(参数..) 返回匹配模式的数组条目,数组中符合正则表达式条件的数组元素 ,并且返回数据类型是数组! 参数列表: 参数1:正则表达式 参数2:检测匹配的数组 索引数组 关联数组 都是可以的! 参数3: 设置结果为正则不匹配的元素组成的数组

案例代码1:

标签:

提交需求或反馈

Demand feedback