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);
I typically read blogs via RSS, clicking through to the actual post when occasion permits. But I'm starting to think I should revisit the main page of some of the blogs I read. Case in point: Snide Remarks.
At some point in the years since I've visited his actual website Eric has changed things up. It used to contain a fairly standard list of posts. Now there's an Excel spreadsheet looking layout. Which is a little odd, if you think about it. But also awesome. Here's why:
This is the latest--and long overdue--installment in a series of posts called Blogs Worth Reading.