Code Snippets

A collection of code snippets and functions that may come in handy for whatever purposes.

PHP Fix Ampersands

/**
* PHP function to convert all HTML ampersand entities (&) in a string to
* HTML encoded & entity as required for XHTML compliance.
* Can be readily copy/pasted as a WordPress filter.
*
* @param string $text text in which to find and fix ampersands
*
*/
function fix_ampersands($text) {
    // don't disturb © { or other entities fix & 'B&O' 'X & Y'
    return preg_replace("'&(?![a-zA-Z0-9#]+;)'is","&", $text);
}

PHP Max String Length

/**
* PHP function to trim a string to a maximum length without cutting off words.
* Useful for creating clean excerpts from blobs.
*
* @param string $text text to trim
* @param int $lim maximum length of excerpt
* @param string $delim delimiter to append if excerpt overruns limit. Defaults
*  to "..."
*
*/
function substr_words($text, $lim, $delim="…")
{
    $len = strlen($text);
    if ($len <= $lim) return $text;

    // split at first word boundary after $lim chars
    preg_match('/(.{' . $lim . '}.*?)\b/', $text, $matches);

    // preg above can result in "hello &amp" without terminal ';'
    $text = preg_replace("'(&[a-zA-Z0-9#]+)$'", '$1;', $matches[1]);
    $text .= $delim;
    return $text;
}
/**
* @class Operations for cookie manipulation
*/
var Cookie = {
    set: function(name, value, seconds){
        value = encodeURIComponent(value);
        if (seconds)
        {
            var d = new Date();
            d.setTime(d.getTime() + (seconds * 1000));
            expiry = '; expires=' + d.toGMTString();
        }
        else
        {
            expiry = '';
        }
        document.cookie = name + '=' + value + expiry + '; path=/';
    },
    get: function(key) {
        key = key.replace(/[-[\]{}()*+?.\\^$|,]/g, "\\$&");
        var value = document.cookie.match('(?:^|;)\\s*' + key + '=([^;]*)');
        return value ? decodeURIComponent(value[1]) : false;
    },
    unset: function(cookie) {
        if (typeof cookie == 'object') this.set(cookie.key, '', -1);
        else this.set(cookie, '', -1);
    }
};