We'll present one algorithm below which demonstrates the use of a loop and the ord function to step through the characters in a string.
In our case, we wish to normalize strings which are formatted as such:
unitedStates, tomSmith, fordFocus
to return their human readable form (United States, Tom Smith, Ford Focus)
If you are not familiar with regular expressions, the following function below serves as a good example:
function normalizeString($tstring) {
$normalizedString = '';
$position = 0;
while($char = substr($tstring, $position, 1)) {
if (ord($char) >=65 && ord($char) <= 90)
$normalizedString .= ' ';
$normalizedString .= $char;
$position += 1;
}
return ucfirst($normalizedString);
}
Now, to do the exact same with regular expressions:
function normalizeString($string) {
return ucfirst(preg_replace('/([A-Z])/', ' $1', $string));
}
In our tests, the regular expression approach ran, on average, 10-15 percent faster than the loop approach.