Jump to content

Archived

This topic is now archived and is closed to further replies.

poirot

"Always Progressive" str_replace?

Recommended Posts

Here is my problem folks:

Sometimes when you need to do simple search and replace you can use str_replace. But let's say you created an encryption scheme, which consists in simple character swapping (like a->8, b->X, and so on). Obviously if you use str_replace it's not going to work, since it will seek the entire string everytime it's called, so some characters could be swapped twice, giving you a bad result.

So, I need something that won't "scan" something that was aleady replaced. I could use a complex code with preg_match , capturing the offsets, and using substr(), but this is kind of annoying. I also tried strtr() but for some reason it's not working as I expected when I use arrays as arguments.

Any ideas?
Thanks in advance. [img src=\"style_emoticons/[#EMO_DIR#]/wink.gif\" style=\"vertical-align:middle\" emoid=\":wink:\" border=\"0\" alt=\"wink.gif\" /]

Share this post


Link to post
Share on other sites
[!--quoteo(post=377494:date=May 27 2006, 02:31 PM:name=poirot)--][div class=\'quotetop\']QUOTE(poirot @ May 27 2006, 02:31 PM) [snapback]377494[/snapback][/div][div class=\'quotemain\'][!--quotec--]
Here is my problem folks:

Sometimes when you need to do simple search and replace you can use str_replace. But let's say you created an encryption scheme, which consists in simple character swapping (like a->8, b->X, and so on). Obviously if you use str_replace it's not going to work, since it will seek the entire string everytime it's called, so some characters could be swapped twice, giving you a bad result.

So, I need something that won't "scan" something that was aleady replaced. I could use a complex code with preg_match , capturing the offsets, and using substr(), but this is kind of annoying. I also tried strtr() but for some reason it's not working as I expected when I use arrays as arguments.

Any ideas?
Thanks in advance. [img src=\"style_emoticons/[#EMO_DIR#]/wink.gif\" style=\"vertical-align:middle\" emoid=\":wink:\" border=\"0\" alt=\"wink.gif\" /]
[/quote]

you can use preg_replace, in a non-greedy mod.

Share this post


Link to post
Share on other sites
Actually non-greedy regex won't help, since after each character it's going to search the entire string again. I don't want parts of the string that were already replaced to be replaced again.

Share this post


Link to post
Share on other sites
I would have suggested strtr().

What is the particular piecs of code that isn't working?

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.