1

So yesterday I asked a question to see if it were possible to remove invalid characters from a string and keeping only a few valid ones for a number formatter ( Removing (nearly) all non-numeric characters from a string)

The answer was excepted and it worked great. But I've been thinking about it and simply removing the invalid characters isn't the correct thing to do. I can't simply assume the rest of the characters that were input were indeed correct, It would be best practice to raise an error.

I'm wondering how I would go about raising an error if any of the characters not mentioned in my $sAllowedValues variable are input

All help appreciated!

The snippet of code validating what characters are allowed

    $sAllowedValues = "/\+?[0-9 EeXxTt]*/";
    preg_match_all($sAllowedValues, $sNumber, $sMatches);
    var_dump($sMatches);
1
  • What exactly are you having problems with? You can compare the original input to the matched content to see if anything was changed; if there were illegal characters in the input. Commented Jun 28, 2016 at 8:41

1 Answer 1

1

Just add the beginning and end of the string match: ^ and $. That way the match will succeed only when the whole string consists of the valid characters

$sNumber = 'a24432';

$sAllowedValues = "/^\+?[0-9 EeXxTt]*$/";
$res = preg_match($sAllowedValues, $sNumber, $sMatches);
var_dump($res); // 1 - OK, 0 - there are invalid chars
Sign up to request clarification or add additional context in comments.

5 Comments

This works great! I have no idea how regular expressions work. Never managed to get my head around them! Thank you!
Just play on regex101 with simple regexp-s for a while and see how the result changes
I've got one more teeny tiny request, how would I go about allowing a '+' through, BUT only if it were in the first position? Again this also being optional as people are allowed to start their inputs with 0? Could this be done or is it complex?
Actually scrap that comment, I have a function I've created that removes the +(44) part at the start of a number, I can have that being used before this function, then not allow any additional + symbols through, thank you!
@JamieBelcher This regexp already does that for you. Again try regex101. Entering TEST STRING "+1111" passes the test while "+1+111" does not

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.