CodeSOD: An Explosion of Strings

Rich was digging through some legacy PHP code, trying to track down where some apparently magical values were coming from. This involved tracing through function after function after function.

Here's a sampling of some of those functions:

function iif($cond,$a,$b) { return $cond?$a:$b; }

iif is a common convention in VB, Excel, and Cold Fusion. That gives us a sense of this developer's background, and the fact that they want to force it into a language where you've already got constructs for inline ifs.

But there's a lovely pile of string mangling:

function append(&$string,$append="<br />") { if(empty($string)) $string = $append; else $string = "$string$append"; } function appendln(&$string,$append="<br />") { if(empty($string)) $string = $append; else $string = "$string\n$append"; } function singleQuote($string) { return "'$string'"; }

Or, the wonderfully potent and common reinvention of numeric parsing:

function str2int($string, $concat = true) { if(is_numeric($string)) return $string; $length = strlen($string); for ($i = 0, $int = '', $concat_flag = true; $i < $length; $i++) { if (is_numeric($string[$i]) && $concat_flag) { $int .= $string[$i]; } elseif(!$concat && $concat_flag && strlen($int) > 0) { $concat_flag = false; } } return (int) $int; }

This parses a string a character at a time, and then turns into a busy loop if it encounters a non-numeric character.

It's okay, though, because if you wanted to split on characters (or "explode" in PHP parlance), there's this handy method.

function explodeByCharacter($delimiters,$str) { $del = array_unique(str_split($delimiters)); $ret = array($str); foreach($del as $cur) { if(empty($ret)) { return array(); } $ret2 = $ret; unset($ret); foreach($ret2 as $s) { $t = explode($cur,$s); foreach($t as $n) { if(!empty($n)) { $ret[] = $n; } } } } return $ret; }

The core logical flow is that they want to split a string by multiple delimiters, and don't want to use regexes. So the core logic is to split the string, then split all the substrings, etc., for every delimiter. But it does this through swapping around temporary variables and unsetting things.

Rich writes:

Need I go on? I haven't even gotten to the date functions yet!

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published. Required fields are marked *