RE: [PHP] running str_replace, it misbehaves!
| From: | Ford, Mike | Date: | Mon, 17 Aug 2009 09:31:10 +0000 |
| Subject: | RE: [PHP] running str_replace, it misbehaves! | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-296869@lists.php.net to get a copy of this message | ||
> -----Original Message-----
> From: Allen McCabe [mailto:allenmccabe@gmail.com]
> Sent: 16 August 2009 22:07
[...]
> Here is an example of my code:
>
> [code]
>
> <?php
> //ENCRYPT FUNCTIONS
> function format_string($string,$functions)
> { $funcs = explode(",",$functions);
> foreach ($funcs as $func)
> {
> if (function_exists($func)) $string = $func($string);
> }
> return $string;
> }
> function enc_string($string)
> { $search =
>
> array("a","b","c","d","e","f","g","h","i","..........");
> //62
> values
> $replace =
> array("j9","k8","q7","v6","..........."); //62
> values
> $string = str_replace($search, $replace, $string);
> $search2 =
>
> array("9k","8q","7v","6w","5x","4y","3z","2j","................");
> // 126
> values
> $string = str_replace($search2, $replace2, $string);
> return $string;
> }
When you feed array search and replace values to str_replace, it runs them in sequence, not in
parallel
As you haven't given us a full input alphabet above (and, incidentally, you've left out
the value of $replace2!), I can't give an example using your encoding, so let's just take,
for example:
$string = 'word';
and feed it through
str_replace(array('d','o','r','w'),
array('w9', 'r8', 'o7', 'd6'), $string);
This proceeds as follows:
d -> w9 = worw9
o -> r8 = wr8rw9
r -> o7 = wo78o7w9 // Note how TWO r->o7 replaces were made here!
w -> d6 = d6o78o7d69 // and similarly w->d6 twice!
I think this gives you a clue as to what is happening -- the same effect will occur on your second
str_replace, as well, giving you your apparent "multiple encode" problem. If you must do
this kind of translation, then you need a function that doesn't have this re-replace effect,
such as strtr() http://php.net/strtr.
But, I have to wonder, why aren't you just using one of the encoding functions readily
available in PHP, such as md5() or sha1(), or hash()?
Cheers!
Mike
--
Mike Ford,
Electronic Information Developer, Libraries and Learning Innovation,
Leeds Metropolitan University, C507, Civic Quarter Campus,
Woodhouse Lane, LEEDS, LS1 3HE, United Kingdom
Email: m.ford@leedsmet.ac.uk
Tel: +44 113 812 4730
To view the terms under which this email is distributed, please go to http://disclaimer.leedsmet.ac.uk/email.htm