Useful PHP functions / snippets

Here are a few useful functions and snippets of PHP code I've written, which may be of use for future projects.

TODO: need to flesh this page out, with a bit of explanation of each snippet etc.

function qw($instr) {
// emulates (kind of) the Perl qw (quote-words) construct
// to allow a list of words to be supplied without quoting.
return (preg_split("/[\b|\s]+/", $instr));
}
function mysql_insert_statement($table, $data) {
    // generate an insert statement to insert the data in $data into $table
 
    $fieldlist = "'" . join("','", array_keys($data))   . "'";
    $valuelist = "'" . join("','", array_values($data)) . "'";
 
    return "INSERT INTO $table ($fieldlist) VALUES ($valuelist);" ;
 
} // end of function mysql_insert_statement
 
 
function mysql_update_statement($table, $condition, $data) {
    // generate an update statement to update the row(s) matching
    // $condition, updating the fields in $data ass. array with the
    // values given.
 
    $fieldlist = "'"  . join("', '", array_keys($data))   . "'";
    $valuelist  = "'" . join("', '", array_values($data)) . "'";
 
    $sql = "UPDATE $table SET ";
 
    $sets = array();
    foreach ($data as $field => $value) {
        $sets[] = "$field = '" . addslashes($value) . "'";
    }
    $sql .= implode(',', $sets);
 
    $sql .= " WHERE $condition;" ;
 
    return $sql;
 
} // end of function mysql_update_statement
function preg_get_match($regexp,$subject) {
// perform a preg_match and return the first match of the first capture
 
    return (preg_match($regexp,$subject,$match))? $match[1] : false;
 
} // end of function preg_get_match()
function rot13($in) {
// perform a simple rot-13 encryption/decryption - NOT secure at all, 
// but obfuscates things a bit, and makes it slightly less obvious 
// what's going on to anyone nosy (never rely on security through
// obscurity though)
 
if ((!isset($in)) || ($in == '')) { return 0; }
 
return strtr($in,
	"NnOoPpQqRrSsTtUuVvWwXxYyZzAaBbCcDdEeFfGgHhIiJjKkLlMm0123456789",
	"AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz5678901234");
 
} // end of function rot13()
function array_to_js($arr,$name,$rec = 0) {
    // converts the given array to a Javascript array.
 
    $out = (!$rec)? "// array_to_js() dumping PHP array to Javascript\n" : '';
    $var = (!$rec)? 'var ' : '';
    $out .= $var . $name. ' = new Array();
    ';
    foreach(array_keys($arr) as $key) {
        if (is_array($arr[$key])) { 
            // it's an array - do that too
            $out .= array_to_js($arr[$key], $name . "['$key']",1);
        } else {
            $out .= $name . "['$key'] = '$arr[$key]';\n";
        }
    }
 
    return $out;
} // end of function array_to_js()
function safe_stream_set_timeout($handle,$timeout) {
    // depending on the version of PHP in use we need to call this function by 
    // different names - the PHP developers were a bit indecisive :)
 
    if (function_exists('stream_set_timeout')) { 
        return stream_set_timeout($handle,$timeout); 
    } elseif (function_exists('socket_set_timeout')) { 
        return socket_set_timeout($handle,$timeout); 
    } elseif (function_exists('set_socket_timeout')) { 
        return set_socket_timeout($handle,$timeout); 
    } else {
        return false;
    }
 
} // end of function safe_stream_set_timeout()
function trim_and_pad($subj, $length) {
    // manipulates the given string and returns a version of it exactly $length 
    // chars long. If string is longer than $length, it'll be cut down, three 
    // dots added to the end, then padded out to $length. If string is shorter, 
    // it'll be padded out with spaces on the right to the desired $length.
 
    if (strlen($subj) == $length) { 
        // nothing to do
        return $subj;
 
    } elseif (strlen($subj) < $length) { 
        // just pad it out to the right length
        return str_pad($subj, $length);
 
    } elseif (strlen($subj) > $length) {
        // string needs trimming...
        return substr($subj, 0, $length - 3) . '...';
    }
 
} // end of function trim_and_pad()

Masking a card number:

$masked = str_repeat('*', strlen($card) -4) . substr($card, -4);
 
php/snippets.txt · Last modified: 2010/02/26 10:45 (external edit)
 
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki