Span Filepaths in WordPress Content

I wanted filepaths and filenames in WordPress post and page content to be displayed with a monospace font, so I wrote the following PHP plugin to wrap filepaths with a <span> HTML and CSS style tag. The code could be added to a theme’s functions.php file, or used as a stand-alone plugin.

The span-filepaths.php script wraps filepaths and filenames with a CSS ID of “span-fp”, and variables / perl module names with a CSS ID of “span-ftp-var”. Here’s an example of a CSS stylesheet:

The script is built around a preg_replace() function (see the preg_replace manual), which allows arrays as arguments for the pattern and replacement strings. When using arrays with preg_replace(), it’s important to ksort() them before-hand (see the ksort manual) so each array has the same order.

The content parsed by the span-filepaths.php script is split into lines to check for comment, script, and pre html tags. The text within those blocks is left as-is to avoid, in the case of javascript for example, breaking code that must be executed by the browser.

I will attempt to document each regular expression within the code. If you have any questions about the regular expressions or the script, feel free to post a comment bellow.

Download the span-filepaths.php script.

If you want to use span-filepaths.php as a WordPress plugin, you’ll need to create a ./wordpress/wp-content/plugins/span-filepaths/ folder, save the span-filepaths.php script in this folder, add a readme.txt file to describe the plugin, and then activate it from the WordPress plugins page.