Posts tagged "php"

Linkify tweets with regex

Regular expressions are powerful, useful, and — in my opinion — lots of fun! Thanks to the prevalence of Twitter, every web developer will be exposed to regex sooner or later: before outputting tweets in HTML, Twitter names and hyperlinks must be wrapped in anchor tags.

Matching @names

Here's the gist: a match will begin with "@" and the at sign must be followed by one or more word (letter / number / underscore) characters. The @name must either appear at the beginning of the tweet or be preceded by a space. This prevents the regular expression from matching "@example" in "me@example.com".

Using HTML5 time element in WordPress themes

I've begun retrofitting this site with HTML5 elements. I'm thoroughly enjoying the process (I love meaningful markup).

One of the first HTML5 elements I've introduced is the time element which, through its datetime attribute, provides a machine-readable version of dates and times.

<time datetime="2009-11-01T16:41:53+13:00">1 November 2009</time>

I wrote a function to generate the machine-readable dates and times for blog comments.

/**
 * echoes comment's date and time in format 2009-11-01T03:41:53+13:00
 */
function comment_datetime()
{
    $comment = get_comment($comment);
    $local = strtotime($comment->comment_date);
    $gmt = strtotime($comment->comment_date_gmt);
    $seconds = abs($local - $gmt);
    $hours = (int) ($seconds / 3600);
    $minutes = (int) (($seconds - $hours * 3600) / 60);
    $output = get_comment_time('Y-m-d\TH:i:s');

    if ($local == $gmt)
        $output .= 'Z';
    else
        $output .= ($local > $gmt ? '+' : '-')
                . str_pad($hours, 2, '0', STR_PAD_LEFT) . ':'
                . str_pad($minutes, 2, '0', STR_PAD_LEFT);

    echo $output;
}

While looping through comments in your WordPress theme, call the above function to print a valid datetime string.

<time datetime="<?php comment_datetime(); ?>">

PHP print_filesize function

Recently I've been on a drive to eliminate dependencies from my code and other areas, such as blog posts. For those who create content for the Web, a reasonably common task is to provide links to files that can be downloaded. It is considered good practice to include an indication of a file's size; for example: favicon.ico (3 KB).

As I was about to hard-code a file's size into a blog post recently, I thought to myself: Will I remember to update this if the file's size changes? More importantly, should I be required to remember such things? The answer, of course, is no. I set about writing a function that would allow the file's size to be displayed dynamically.

PHP brush for SyntaxHighlighter

Alex Gorbatchev's SyntaxHighlighter is a well-written bundle which enables syntax highlighting of code via JavaScript. More than twenty languages are supported "out of the box", and brushes (JavaScript files containing language-specific regular expressions) can be created to support additional languages.

Unfortunately, however, several of the brushes that come bundled with SyntaxHighlighter are far from perfect. Have a look at the bundled PHP brush in action below.

Screenshot of PHP code highlighted by SyntaxHighlighter's PHP brush
Screenshot of bundled PHP brush in action

Looping more than once with the WordPress loop

When I decided to write my own WordPress theme, I thought a good approach would be to duplicate the default theme and go from there. Since that day I have rewritten much of the code. The loop in the index.php file, however, remains unchanged. The loop looks like this:

if (have_posts()) :
    while (have_posts()) : the_post();
        // code
    endwhile;
endif;

As well as displaying the three most recent posts on the home page, I wanted to display links to slightly older posts on the sidebar. I discovered a WpRecipes post on using two different WordPress loops which suggests adding the following line of code just before the loop:

query_posts('showposts=5&offset=3');

The offset ensures that posts do not appear in both places.

WordPress login redirect

Sometimes we require users to log in to a WordPress site in order to access front-end functionality hidden from guests. In such instances, we can simply provide a standard login link:

<a href="<?php bloginfo('url'); ?>/wp-login.php">log in</a>

While this gets the job done, it takes users to the dashboard after they have logged in: they must then click on a link to return to the front-end, at which point an additional click may be required to get them back to the page they were viewing. Since WordPress 2.6.2 it has been possible to circumvent this round trip from origin to wp-login.php to wp-admin/ to / and finally back to origin by including a value for redirect_to in the href:

<a href="<?php bloginfo('url'); ?>/wp-login.php?redirect_to=<?php echo urlencode($_SERVER['REQUEST_URI']); ?>">log in</a>

The above returns users to their starting point after they've logged in.

Escape special characters for SQL REGEXP

Developers will be familiar with using PHP's mysql_real_escape_string to escape problematic characters before submitting a query. When the query in question involves MySQL's REGEXP function, however, we need to go one step further and escape regex's special characters.

Intelligent CSS caching

If you've ever worked with CSS, you'll understand how frustrating it is to edit a style sheet and be unable to view the change because a cached version of the file is being used. One line of PHP will fix this problem, and will also ensure that visitors never view your site through the lens of an outdated style sheet.