user2113177 user2113177 - 4 months ago 32
PHP Question

PHP: Check if string contains characters NOT in array

I want to validate that a string consists of numbers or commas or semicolons:

valid:

1.234

valid:
1,234

invalid:
1.23a

invalid:
1.2_4


What works:

use
str_split
to create an array out of the string and use
in_array
with
array(0,1,2,3,4,5,6,7,8,9,',',';')
.

But this feels circuitous to me and since I have to do this with millions of strings I want to make sure there is no more efficient way.

Question: Is there a more efficient way?

Answer

If you only need to validate a string (not sanitize or modify it), you can use regex. Try the following:

if (preg_match('/^[0-9\,\;\.]+$/', $string)) {
     // ok
} else {
    // not ok
}