Deprecated Behaviour

The inane, sometimes insane, ramblings from the mind of Brenton Alker.

Trim() Validation

While writing a fairly standard sign-up/log-in system, I got to the point of validating the password to make sure it only contained acceptable characters. Now for me this would usually mean a regular expression. But, since this system wasn’t for me I decided to make the “valid characters” configurable, and generally the people configuring it won’t be able to write a regular expression.

My solution is to use php’s trim() (or more specifically rtrim(), but it doesn’t really matter) by passing the users input as the first argument, and the string of valid characters as the second; I should get an empty string in return. So the test, only allowing lowercase letters, becomes:

1
2
3
4
<?php
    if ('' !== rtrim($input, 'abcdefghijklmnopqrstuvwxyz')) {
    return false;
    }

Simple! I don’t know how it compares speed wise with other methods, but it seems simple and effective and I can’t imagine it’s terribly slow unless your strings get larger.

I’m also not sure how it would handle multi-byte characters. But I don’t think it would be a problem if it doesn’t. Anyone got any insight?