Check whether string contains numbers

Hi Guys!

I need to check whether a string contains numbers. What would be the best way to achieve this.

For example:


xxx123   would return true
xxx        would return false
x1x2x3   would return true
123       would return true

Any ideas?


if(1 === preg_match('~[0-9]~', $string)){
    #has numbers
}

You could use a Regular Expression solution:


function ContainsNumbers($String){
    return preg_match('/\\d/', $String) > 0;
}

Edit:

Darn, beaten to it!

1 Like

Or if you want something that will allow you to spend some quality time later on deciding exactly what is going on, you can use the completely unobvious choice of strpbrk. (:

// TRUE if $subject contains a decimal digit
strpbrk($subject, '1234567890') !== FALSE
Off Topic:

Does no-one like just casting to bool?.. ponders

Off Topic:

I donā€™t, I prefer to be a little more explicit. Given phpā€™s loose typing, or rather the handling of it, I do worry that the casting behaviour is somewhat uncertain.

[fphp]strpbrk/fphp huh? I wonder what it stands forā€¦ It looks like ā€˜Spring Breakā€™. :cool:

[ot]> I donā€™t, I prefer to be a little more explicit. Given phpā€™s loose typing, or rather the handling of it, I do worry that the casting behaviour is somewhat uncertain.

Could you give any examples to clarify your uncertainty? Casting the result to bool will do, to my understanding, the same as your comparison to 1 (since TRUE will never be returned); Iā€™m not sure where your worries over loose typing come into play? :confused:

> [fphp]strpbrk/fphp huh? I wonder what it stands forā€¦ It looks like ā€˜Spring Breakā€™. :cool:

I cannot answer this authoritatively but I believe comes from ā€œstring [return] pointer [to] breakā€ (see GNU C lib manual page for string search functions). As logical a function name as any. :shifty:
[/ot]