0

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?

4

1 回答 1

2

Go with the easier to read. You can soon optimise it in the future if you ever found that to be the bottle neck (which i doubt it ever will be). You will find that you will be glad of going with the easier to read version in 6 months time when you need to update it due to a regex bug you have found ;)

Remember, languages have the ability to leave "comments" to help you make code easier to read at a later date ;)

于 2012-11-18T02:37:20.823 回答