2

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?

1
  • Inverting the character class / allowed characters and negating the return of preg_match() is likely to perform better than matching the whole string. In other words, stop searching the string as soon as a character that is not in your white list is found in the string. Commented Mar 12, 2022 at 12:13

2 Answers 2

5

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

this approach will return false("not ok") for the input 1.234. While the OP expects it to be valid: valid: 1.234 valid: 1,234 invalid: 1.23a invalid: 1.2_4
@Nitin I think, he intended float numbers ... I suppose
@RomanPerekhrest you are right. I only realized that after going through the question again. But, there was no dot in the array either.
2

The solution using preg_match function:

// using regexp for (numbers OR commas OR semicolons) - as you've required
function isValid($str) {
    return (bool) preg_match("/^([0-9.]|,|;)+$/", $str);
}

var_dump(isValid("1.234"));  // bool(true)
var_dump(isValid("1.23a"));  // bool(false)
var_dump(isValid("1,234"));  // bool(true)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.