neemzy's snippets - Page 4 of 5

Useful for Symfony2 or Silex as they load an instance of the app in Twig, this snippet allows to check if you're currently at its root, no matter it's in a subdirectory on your web server or not.

{% if app.request.getRequestURI()|rtrim('/') == app.request.getBasePath() %}
    {# do something #}
{% endif %}

Use this to get a summary for a blog article, for example : it returns a tag-stripped substring, cut at the end of the last entire word, appended with ellipses if necessary.

function getSummary($text, $length = 150)
    $text = trim(preg_replace('~(\s+)~', ' ', strip_tags($text)));
    if (strlen($text) > $length)
        $cut = substr($text, 0, $length);
        if (substr($text, $length, 1) != ' ')
            $cut = substr($cut, 0, strrpos($cut, ' '));
        $text = $cut.'...';
    return $text;

Just a quick tip to extend jQuery so you can set or unset a class to an element (or group of elements) depending on a boolean condition :

$.fn.setClass = function(myclass, action) {
    this.hasClass(myclass) == !! action || this.toggleClass(myclass);
    return this;

// Then do
$('#myelement').setClass('americaine', myBooleanFunction());

This snippet includes two functions : one that retrieves an array's longest row length, and another that transposes it according to the title (and depends on the first). It can come handy when needing to access simple data the other way around.

function array_longer_row($array)
    $max = 0;
    $lens = array();
    foreach ($array as $row)
        $len = 1;
        if (is_array($row))
            $len = count($row);
        $lens[] = $len;
    return max($lens);

function array_transpose($array)
    $result = array();
    $max = array_longer_row($array);
    for ($i=0;$i<$max;$i++)
        $result[$i] = array();
        foreach ($array as $key => $row)
            if (is_array($row))
                $row = array_values($row);
                $row = array($row);
            if (isset($row[$i]))
                $result[$i][] = $row[$i];
    return $result;

Here's a quick function that may be useful if you have to compare a bunch of value in a row. You can pass your parameters to it directly, as an array or as a JS object. It depends on jQuery for array/object conversion as IE < 9 doesn't know

function anymax()
    var argv = anymax.arguments, argc = argv.length, max = false;

    if (argc)
        max = argv[0];

        if (typeof max === 'object')
            argv =, function(v, k) { return v; });
            max = argv[0];

        for (i in argv)
            max = Math.max(max, argv[i]);

    return max;

This little trick might be useful if you want your text to break at a specific point when handling it with media queries or something.

/** Notice the extra space to prevent the wrapping words from sticking to each other **/
<p>I want my text to break <br />right here.</p>

/** This will cancel the line-break **/
p br { display: none; }

/** This will restore it **/
p br { display: block; }

This couple of simple URL rewriting rules will help you avoid some mistakes that are syntaxically legal and therefore might be referenced upon a bad backlink to your website or something.

# Multiple slashes
RewriteCond %{THE_REQUEST} \ (.*)//+(.*)\  [NC]
RewriteRule ^(.*)$ %1/%2 [L,R=301]
# Trailing dot on domain
RewriteCond %{HTTP_HOST} (.*)\.$
RewriteRule ^(.*)$ http://%1/$1 [L,R=301]
# Trailing question mark
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /[^\ \?]*\?($|\ )
RewriteRule ^(.*)$ /$1? [L,R=301]
# Trailing slash(es)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ http://%{HTTP_HOST}/$1 [L,R=301]

If you're using Shadowbox and the likes, some of your elements' rel attributes might come with fancy values the W3C validator won't like. Put these values in data-rel instead, and use the following :

jQuery('[data-rel]').each(function() {
    var that = jQuery(this);
    that.attr('rel', function(i, val) { return ((typeof val === 'undefined') ? '' : val+' ')'rel'); }).removeAttr('data-rel');

This function has the behavior many of us dreamed of for its JS homonym !

function parseInt($s) {
    return ((int) preg_replace('~[^0-9]+~', '', $s));

This function allows you to switch between SQL (YYYY-MM-DD) and "human-readable" (DD/MM/YYYY) date formats at the speed of light. No calculations, only string manipulation !

function switchDF($date) {
    $s = array("-", "/");
    for ($i=0;$i<count($s);$i++) {
        $date = explode($s[$i], $date);
        if (count($date) == 3) return $date[2].$s[(int)!$i].$date[1].$s[(int)!$i].$date[0];
        else $date = $date[0];
    return false;