snippet

If, like me, you hose Apache on your Ubuntu LTS server when you finally get around to upgrading libssl, and PHP stops working...

You'll be needing this:

apt-get --reinstall install apache2 php5-mysql \
libapache2-mod-php5 mysql-server

(You're welcome)

Preparing a string for use in a PHP regular expression.

This blog post is just for me, so I can look it up later... I suppose you can borrow it if you find it useful :)

Using dynamic strings inside a regex can be annoying, especially if you can't guarantee that the strings are actually sane. Including a URL in a regular expression is downright obnoxious, since URLs and regular expressions share most of the same special characters, but they mean entirely different things. I threw this function together to make strings regexable. Enjoy.

Function

/**
 * Prepare a string for use in a regular expression.
 * 
 * @author Justin Hileman {@link http://justinhileman.com}
 * @access public
 * @param string $str
 * @return string
 */
function preg_real_escape_string($str) {
    $replace = array('\\' => '\\\\', '^' => '\^', '.' => '\.',
        '$' => '\$', '|' => '\|', '(' => '\(', ')' => '\)',
        '[' => '\[', ']' => '\]', '*' => '\*', '+' => '\+',
        '?' => '\?', '{' => '\{', '}' => '\}', ',' => '\,');
    return strtr($str, $replace);
}

Yeah, the name is a bit weird. This function is an analog to mysql_real_escape_string(), so it seemed fitting.

Usage

// basic usage (this is actually exactly the case I wrote this function for).
$regex = '/^' . preg_real_escape_string($name) . '/i';
$nameless = preg_replace($regex, '', $something_starting_with_name);
 
// trying to find a URL via regex can be especially obnoxious.
$regex = '/' . preg_real_escape_string($my_url) . '/';
$some_text = preg_replace($regex, '<a href="$1">$1</a>', $some_text);

Command-line batch cron processing for Drupal

In which our hero carries on the time-honored tradition of posting some random snippet to his blog because he might wish to reference it later.

I occasionally need Drupal to execute its cron handler more than once. Today, I was trying to regenerate api documentation for about 18,000 files, which, understandably, is broken up into several cron runs. If I wait for the natural course of things, the documentation will take about three days to regenerate. If I run cron as fast as I can, it usually finishes in less than an hour. So here's the snippet. Paste this bad boy in your favorite shell.

while true; do /usr/bin/wget -O - -q http://example.com/cron.php; done

When you're done, hit ctrl+C to end the loop.

Note that each wget call blocks until it's finished, so you don't get a bunch of wget processes spawned. Basically it ensures that the next cron job is started as soon as possible after the previous one finishes.

more jQuery typography

You should check out "Use the Best Available Ampersand" from SimpleBits. I love me some ampersands, and that post is a great resource for prettifying your site's ampersands with a little CSS typography.

Along the lines of last week's jQuery "widon't" post, you can offload some of the typography processing to the browser. It's really slick and simple if you have jQuery enabled.

To use some of his ampersandy style goodness, add this JavaScript snippet to your site somewhere:

jQuery(function($){
 
$('h1,h2,h3,h4,h5,h6').each(
    function(){
        $(this).html($(this).html().replace(/&amp;/g,'<span class="amp">&amp;<\/span>'));
    }
);
 
});

Then simply add a few CSS font style rules to your site's stylesheets for span.amp, and you're set.

If you want to be really rad, you could combine this with widon't, like so:

jQuery(function($){
 
$('h1,h2,h3,h4,h5,h6').each(
    function(){
        $(this).html($(this).html().replace(/&amp;/g,'<span class="amp">&amp;<\/span>').replace(/\s([^\s>]{0,10})\s*$/,'&nbsp;$1'));
    }
);
 
});

Now your website is 2x hotter, guaranteed :)

Updated, per Paul's comment, to use jQuery's $.html instead of manipulating innerHTML on the actual DOM elements. Also updated to use a DOM ready callback, making it easier on folks who just want to copy/paste these snippets into their site.

A jQuery "widon't" snippet

In the interest of more attractive Internets, here's a quick little javascript "widon't" snippet—written in jQuery—that I've been using. Now go do something cool with it.

jQuery(function($){
 
$('h1,h2,h3,li,p').each(
    function(){
        $(this).html($(this).html().replace(/\s([^\s<]+)\s*$/,'&nbsp;$1'));
    }
);
 
});

Feel free to replace or augment the selector ('h1,h2...p') with any additional elements you'd like to see widon'ted.

I actually use this variant, which lets longer words be widows if they wanna:

jQuery(function($){
 
$('h1,h2,h3,li,p').each(
    function(){
        $(this).html($(this).html().replace(/\s([^\s<]{0,10})\s*$/,'&nbsp;$1'));
    }
);
 
});

Note: Dave Cardwell posted a jQuery widon't a couple of years ago, but holy balls it's big... If you want something a bit more robust, be sure to check his out.

Another note: I added newlines and tabs to make the code more readable. If I were you, I'd remove those bad boys before deploying.

Update: I wrapped the snippets in a DOM ready callback, making it easier for those who just want to copy/paste these snippets into their site.

wrand(); // a php weighted randomization function

dan from todaywasawesome just asked me to help him with a weighted randomization function in php. i thought my solution was cool, if a bit simplistic. like everything else i want to keep around, i'm posting it in my blag. enjoy!

/* this function expects either an array
 * ordered by weight, or with exact weights
 * as it's array indices.
 * it will return a randomly selected value.
 */
function wrand($data) {
    $totalw = $curw = 0;
 
    foreach ($data as $i => $val) {
        $totalw += $i;
    }
 
    $rand = rand(0,$totalw);
 
    foreach ($data as $i => $val) {
        if ($curw >= $rand) return $val;
        $curw += $i;
    }
 
    return array_pop($data);
}

uberquick comments in html/xhtml

Ajaxian just featured a rad comment hack, originally posted by Dirk Ginader, for those times when you need to comment and uncomment a section of code a bunch. By adding or removing just one character you can comment/uncomment an entire block of code. This saves a bunch of time, and works great for just about any language that uses C style commenting.

Here's how to do it with (X)HTML:

<!--
<p>lorem ipsum dolor</p>
<!-->

just add a >, to uncomment the whole section.

<!-->
<p>lorem ipsum dolor</p>
<!-->

This seems to work in any browser, and validates as both HTML 4 and XHTML strict.

Snippet of the day: Trim a string (the smart way) with PHP

I reworked the feed reading signature images I made a while back and added something to trim the strings to a decent length without breaking words. So here you go. A one-liner that will trim a string to a decent length, and break it on whitespace:

if (strlen($blog_title) > 35) $blog_title =
array_shift(explode("|||", wordwrap($blog_title,
35, "|||"))) . "...";