I was writing some code to output HTML links and it ended up like this:
$search = array('/{LINK([^.]*)\.([^.]*)\.([^}]*)}/', '/{ILINK([^.]*)\.([^.]*)\.([^}]*)}/');
$replace = array('<a href="$1.php?$2">$3</a>', '<a class="ilink" href="$1.php?$2">$3</a>');
$foo = preg_replace($search, $replace, $foo);
But then I looked at all the duplication and I tried to find a "better" method. So I ended up with this:
$foo = preg_replace_callback ('/{(I?)LINK([^.]*)\.([^.]*)\.([^}]*)}/', '_rep', $foo);
function _rep($m) {
$x = ' href="'.$m[2].'.php?'.$m[3].'">'.$m[4].'</a>';
if($m[1]) { return '<a class="ilink"'.$x; }
return '<a'.$x;
}
They both return the exact same output. The first one is easier to read. The second one only has to run half as many regexps. But I'm not sure which one is faster, less intensive, and just plain better to use.
Any advice?