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?
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;
}
Darn, beaten to it!
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
Does no-one like just casting to bool?.. ponders
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ā.
[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?
> [fphp]strpbrk/fphp huh? I wonder what it stands for⦠It looks like āSpring Breakā.
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.
[/ot]