Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regex any number

Tags:

regex

php

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
...
like image 630
GDY Avatar asked Nov 30 '25 03:11

GDY


2 Answers

[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.

like image 62
Adam Avatar answered Dec 01 '25 16:12

Adam


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.

like image 41
A. L Avatar answered Dec 01 '25 16:12

A. L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!