Man owns his entire existence to the stateGeorg Wilhelm Friedrich Hegel
Relates to PHP and Web Standards
Many code snippets for handling acronyms seem to rely on <a href="http://www.php.net/preg_replace" title="PHP Doc for preg_replace">preg_replace()</a>. The problem with this method is ensuring that double replacements do not occur (e.g. with XHTML and HTML). A much better function to use is <a href="http://www.php.net/strtr" title="PHP Doc for strtr">strtr()</a> with two arguments:
$translation_array = array(
'XHTML' => '<acronym title="eXtensible Hypertext Markup Language">',
'HTML' => '<acronym title="Hypertext Markup Language">'
);
$str = strtr($str, $translation_array);
It will always look for the longest pattern first and will not try to replace stuff it has already worked on. It is also really quick.
I have been test running the following function on this site to automate acronym handling:
function ss_fns_parse_acronyms($copy) {
static $trans = array();
if (empty($trans)) {
$dat_file = SOME_PATH . '/data/acronyms.dat';
$acronyms = parse_ini_file($dat_file);
foreach($acronyms as $a => $d) {
$trans[$a] = "<acronym title=\"$d\">$a</acronym>";
}
}
return strtr($copy, $trans);
}
The acronyms can be stored in php_ini format in a file, thus new acronyms can be added without interfering with this code. There are occassional limitations and gotchas - e.g. OS inadvertantly appearing in $_POST, but it is an efficient and clean alternative to preg_replace.
Posted on Friday, Aug 13, 2004 at 05:58:50.
Comments on Simple Acronym Handler (0)