Code Snippets

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

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);
}

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;
}