0

While delving into some old code I've stumbled upon a function which is used to clean up special characters using preg_replace very excessively. Unfortunatly there's no way to avoid this cleanup, the messed up data arrive from outside.

/* Example 1: current code */
$item = preg_replace('/' . chr(196) . '/',chr(142),$item);
$item = preg_replace('/' . chr(214) . '/',chr(153),$item);
$item = preg_replace('/' . chr(220) . '/',chr(154),$item);

Alot of those lines are in there, and all do the same (using different characters), so there should be a better way to do this. My first iteration to optimize this would be to use an indexed array, like this:

/* Example 2: slightly optimized code */
$patterns = array();
$patterns[0] = '/'.chr(196).'/'; 
$patterns[1] = '/'.chr(214).'/';
$patterns[2] = '/'.chr(220).'/';

$reps = array();
$reps[0] = chr(142); 
$reps[1] = chr(153);
$reps[2] = chr(154);

$item = preg_replace($patterns,$reps,$item);

It does the job, but I guess there's somewhere a better and/or faster way of doing this alot easier and smarter - maybe even without preg_replace. Due to the early morning and/or the lack of good coffee, I was unable to find it myself so far.

Any suggestions?

Bjoern
  • 15,934
  • 4
  • 43
  • 48

5 Answers5

6

As far as you're concerned to replace characters, you can make use of strtrDocs which has a nice array parameter:

$map = array(
  chr(196) => chr(142), 
  chr(214) => chr(153),
  chr(220) => chr(154),
);

$item = strtr($item, $map);
hakre
  • 193,403
  • 52
  • 435
  • 836
2

I think you could use str_replace for this use. Not sure about the characters you're replacing tho. But if str_replace works, it'll be a lot faster than those preg_replace.

But, does those lines slow your application too much or is it just a case of seeing something you could clean up? Because if it is, don't forget to prepare enough tests to avoid creating problems.

Arkh
  • 8,416
  • 40
  • 45
  • Aye, it is just a case of seeing something which can be cleaned up. Performance really isn't the issue here (at least not at the moment). And yes, I did prepare some tests before starting this. – Bjoern Aug 22 '11 at 08:06
1

You should use strtr here.

$item = strtr($item, chr(196) . chr(214), chr(142) . chr(153));

http://php.net/manual/en/function.strtr.php

Dogbert
  • 212,659
  • 41
  • 396
  • 397
1

You need not regexp to this operation(replacing constant string to another), str_replace enough for you here. Besides, str_replace allows to replace array by array as you want

RiaD
  • 46,822
  • 11
  • 79
  • 123
1

preg_replace or str_replace will both be slower than strtr which is designed for exactly this purpose.

echo strtr("This is a test","aiu","AIU");

will give

ThIs Is A test
mvds
  • 45,755
  • 8
  • 102
  • 111