Eli Fulkerson .com HomeProjectsPhp-string-prefix
 

PHP String Prefix Function

Description:

This is a (probably unnecessary and redundant) function and test function for determining whether or not one string is the prefix of another in php. This is probably something that can be more trivially done with basic strong operations. However, I switch languages a lot and tend to prefer things to be more explicit. You could probably do either of these in one line with a preg_match() type call.

<?

// PRE:  $word and $prefix are both strings
// POST:  returns 1 if either is a prefix for the other, returns 0 otherwise

function prefix( $word, $prefix) {
        if ( strlen($word) < strlen($prefix)) {
                $tmp = $prefix;
                $prefix = $word;
                $word = $tmp;
        }

        $word = substr($word, 0, strlen($prefix));

        if ($prefix == $word) {
                return 1;
        }

        return 0;
}

// PRE:  $a and $b are strings.
//       $type is whether the data *should* be prefix.  1 for yes, 0 for no
// POST:  echos either "OK\n" or "NOT OK\n" to stdout
function test_prefix( $a, $b, $type) {

        $match = 0;

        if (prefix($a,$b) and prefix($b,$a)) {
                $match = 1;
        }

        if ($match == $type) {
                echo "OK\n";
        } else {
                echo "NOT OK\n";
        }

}


test_prefix("hat", "cat", 0);
test_prefix("fire", "fireman", 1);
test_prefix("fireman", "fire", 1);

>>